How to test after_initialize callback of a rails model?

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.


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