I\'m testing a model with an after create callback that I\'d like to run only on some occasions while testing. How can I skip/run callbacks from a factory?
c
In my case I have the callback loading something to my redis cache. But then I did not have/want a redis instance running for my test environment.
after_create :load_to_cache
def load_to_cache
Redis.load_to_cache
end
For my situation, similar to above, I just stubbed my load_to_cache method in my spec_helper,
with:
Redis.stub(:load_to_cache)
Also, in certain situation where I want to the test this, I just have to unstub them in the before block of the corresponding Rspec test cases.
I know you might have something more complicated happening in your after_create or might not find this very elegant. You can try to cancel the callback defined in your model, by defining an after_create hook in your Factory (refer to factory_girl docs), where you can probably define a the same callback and return false, according to the 'Canceling callbacks' section of this article. (I am unsure about order in which callback are executed, which is why I didn't go for this option).
Lastly, (sorry I am not able to find the article) Ruby allows you to use some dirty meta programming to unhook a callback hook (you will have to reset it). I guess this would be the least preferred option.
Well there is one more thing, not really a solution, but see if you can get away with Factory.build in your specs, instead of actually creating the object. (Would be the simplest if you can).