I am trying to write a test for a model which is working perfectly - but for some reason the test is not returning the expected result.
The test is not returning the expected result because the after_validation
callback is never called which is why conference
attribute is nil
. So @plan.conference
is nil and you cannot call empty?
on nil
object. Hence, the error undefined method 'empty?' for nil:NilClass
@plan = build(:plan)
would just create an instance of Plan
model as per the attributes specified in factory :plan
and assign it to instance variable @plan
. It will definitely not run any validations and obviously no ActiveRecord
callbacks.
Just change the before block as
before (:each) do
@plan = create(:plan) ## create record in database
end
With this your after_validation
callback would be triggered as you actually create a record in database.
For reference:
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.