Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 583
MMore Avatar asked Sep 13 '11 07:09

MMore


2 Answers

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.

like image 178
Orlando Avatar answered Sep 21 '22 22:09

Orlando


Orlando's method works, and here's another which I'd like to add. (Using new rspec 'expect' syntax)

expect_any_instance_of(Model).to receive(:method_here)
Model.new
like image 20
Yoopergeek Avatar answered Sep 23 '22 22:09

Yoopergeek