I had a method in a model:
class Article < ActiveRecord::Base
def do_something
end
end
I also had a unit test for this method:
# spec/models/article_spec.rb
describe "#do_something" do
@article = FactoryGirl.create(:article)
it "should work as expected" do
@article.do_something
expect(@article).to have_something
end
# ...several other examples for different cases
end
Everything was fine until I found it's better to move this method into a after_save
callback:
class Article < ActiveRecord::Base
after_save :do_something
def do_something
end
end
Now all my tests about this method broken. I have to fix it by:
- No more specific call to
do_something
becausecreate
orsave
will trigger this method as well, or I'll meet duplicate db actions. - Change
create
tobuild
- Test respond_to
Use general
model.save
instead of individual method callmodel.do_something
describe "#do_something" do @article = FactoryGirl.build(:article) it "should work as expected" do expect{@article.save}.not_to raise_error expect(@article).to have_something expect(@article).to respond_to(:do_something) end end
The test passed but my concern is it's no longer about the specific method. The effect will be mixed with other callbacks if more added.
My question is, is there any beautiful way to test model's instance methods independently that becoming a callback?