【发布时间】:2013-05-21 19:12:54
【问题描述】:
我在模型中有一个方法:
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 - 测试respond_to
-
使用通用的
model.save而不是单独的方法调用model.do_somethingdescribe "#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
测试通过了,但我担心它不再是具体的方法。 如果添加更多,效果将与其他回调混合。
我的问题是,有没有什么漂亮的方法可以独立测试模型的实例方法,使其成为回调?
【问题讨论】:
-
尚不清楚为什么您的原始方法仍不能用于测试。直接对方法进行单元测试,并仅测试它是否被独立地作为回调调用。是我遗漏了什么,还是您不喜欢这种方法?
-
@AndrewHubbs,感谢您的提问。原因是这种方法改变了 db.例如,它将这篇文章分配给类别“Rails”。重构为回调后,当我调用FactoryGirl.create时,该回调将生效并将文章分配到“Rails”类别。当我在测试中再次调用此方法时,会出现错误,因为它已经分配了。
标签: ruby-on-rails ruby-on-rails-3 activerecord rspec factory-bot