Search code examples
ruby-on-railsruby-on-rails-3rspecrspec2rspec-rails

How to test after_initialize callback of a rails model?


I am using FactoryGirl and Rspec for testing. The model sets a foreign key after init if it is nil. Therefore it uses data of another association. But how can I test it? Normally I would use a factory for creation of this object and use a stub_chain for "self.user.main_address.country_id". But with the creation of this object, after initialize will be invoked. I have no chance to stub it.

after_initialize do
  if self.country_id.nil?
    self.country_id = self.user.main_address.country_id || Country.first.id
  end
end

Any idea?


Solution

  • Ideally it's better that you test behavior instead of implementation. Test that the foreign key gets set instead of testing that the method gets called.

    Although, if you want to test the after_initialize callback here is a way that works.

    obj = Model.allocate
    obj.should_receive(:method_here)
    obj.send(:initialize)
    

    Allocate puts the object in memory but doesn't call initialize. After you set the expectation, then you can call initialize and catch the method call.