我在模型中有一个方法:
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
也将触发此方法,否则我将遇到重复的db操作. - 把
create
换成build
- 测试响应
-
使用常规
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
测试通过了,但我担心的是,这不再是具体的方法.效果是mixed with other callbacks if more added.
我的问题是,有没有什么漂亮的方法来测试model的实例方法independently,使其成为回调?