我在模型中有一个方法:
class Article < ActiveRecord::Base
def do_something
end
end
我也对这个方法进行了单元测试:
# 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
一切都很好,直到我发现最好将此方法移动到after_save
回调中:
class Article < ActiveRecord::Base
after_save :do_something
def do_something
end
end
现在我所有关于这种方法的测试都被打破了。我必须通过以下方式修复它:
- 没有更具体的调用,
do_something
因为create
或者save
也将触发此方法,否则我将遇到重复的数据库操作。 - 更改
create
为build
- 测试 response_to
使用通用
model.save
而不是单独的方法调用model.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
测试通过了,但我担心的是它不再是具体的方法。如果添加更多,效果将与其他回调混合。
我的问题是,有没有什么漂亮的方法可以独立地测试模型的实例方法,而不是成为回调?