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.newcall (whereModelis the model class being tested). In your case,Model.newdoesn't produce a valid object so you need to tell Rspec what subject to use for those tests:You should also fix your
correct_datevalidation method to handleoccurred_at.nil?; either validate that it isn'tnilincorrect_date:or validate the presence separately and skip the
>whenoccurred_at.nil?:Making the
occurred_atcolumn in the databasenot nullwould also be advisable.If
occurred_atis truly optional, then you'd only need to updatecorrect_dateto account foroccurred_at.nil?: