I am writing tests for an application and ran into a problem.
I have the next validation im my model:
def correct_date
errors.add(:occured_at, 'must be in past or present time') if occured_at > 5.minutes.from_now
end
And when I run even the simplest tests on the model, they fail.
describe 'associations' do
it { should belong_to(:category).optional }
end
I get an error:
Failure/Error: errors.add(:occured_at, 'must be in past or present time') if occured_at > 5.minutes.from_now
NoMethodError:
undefined method `>' for nil:NilClass
By default, that test will create a new object with a simple
Model.new
call (whereModel
is the model class being tested). In your case,Model.new
doesn't produce a valid object so you need to tell Rspec what subject to use for those tests:You should also fix your
correct_date
validation method to handleoccurred_at.nil?
; either validate that it isn'tnil
incorrect_date
:or validate the presence separately and skip the
>
whenoccurred_at.nil?
:Making the
occurred_at
column in the databasenot null
would also be advisable.If
occurred_at
is truly optional, then you'd only need to updatecorrect_date
to account foroccurred_at.nil?
: