Callback and Callback behavior are independent tests. If you want to check an after_save callback, you need to think of it as two things:
- Is the callback being fired for the right events?
- Is the called function doing the right thing?
Assume you have the Article
class with many callbacks, this is how you would test:
class Article < ActiveRecord::Base
after_save :do_something
after_destroy :do_something_else
...
end
it "triggers do_something on save" do
expect(@article).to receive(:do_something)
@article.save
end
it "triggers do_something_else on destroy" do
expect(@article).to receive(:do_something_else)
@article.destroy
end
it "#do_something should work as expected" do
# Actual tests for do_something method
end
This decouples your callbacks from behavior. For example, you could trigger the same callback method article.do_something
when some other related object is updated, say like user.before_save { user.article.do_something }
. This will accomodate all those.
So, keep testing your methods as usual. Worry about the callbacks separately.
Edit: typos and potential misconceptions
Edit: change "do something" to "trigger something"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…