我的 Rails 模型:任务 has_many 职位。
场景:当我创建一个新职位时,它应该为自己创建一个任务。我想测试一下,我正在这样做:
context "creating a new position" do
let(:position) { create :position, name: 'Read some books', :task => nil }
it "should create a simple task" do
Task.find_by_name('Read some books').should be_nil # First should
position # Execute let() block (FactoryGirl is lazy evaluating)
Task.find_by_name('Read some books').should_not be_nil # Second (more relevant) should
end
end
那么我应该如何改进我的测试呢?第一个“应该”只是确保没有任务,因此我们可以确定创建职位会创建任务。但这违反了“只有一个应该每个它块”的原则。那么这个呢?
context "creating a new position" do
let(:position) do
position = create :position, name: 'Read some books', :task => nil
Task.delete_all
position
end
it "should create a simple task" do
position # Execute let() block (FactoryGirl is lazy evaluating)
Task.find_by_name('Read some books').should_not be_nil
end
end
还是我应该简单地指望无论如何都不应该有这样的任务(因为一个干净的测试数据库不会有一个)?感谢您的意见。
更新(解决方案)
经过一番研究,我找到了change
RSpec 的匹配器:
let(:position) { create :position, name: 'Read some books', :task => nil }
it "should create a simple task" do
# Thanks to FactoryGirl's lazy evaluation of let(), the position doesn't yet exist in the first place, and then after calling position in the expect{} block, it is created.
expect { position }.to change{ Task.count(conditions: { name: 'Read some books' }) }.by(1)
end