我建议通过重新定义的受试者(使用stabby lambdas为了好玩)干燥起来:
describe "recipe creation" do
subject { -> { click_button submit } }
it { should change(Recipe, :count).by(1) }
it { should change(Ingredient, :count).by(1) }
end
更新:虽然它可能看起来不那么干的,这些天我可能仍然会继续使用expect
语法,因为它的recommended,我通常从should
远离,但也许对规格readabi做一些小的更改lity:
describe "recipe creation" do
let(:creating_a_recipe) { -> { click_button submit } }
it "changes the Recipe count" do
expect(creating_a_recipe).to change(Recipe, :count).by(1)
end
it "changes the Ingredient count" do
expect(creating_a_recipe).to change(Ingredient, :count).by(1)
end
end
注意:你可以在expect
使用大括号的RSpec documentation for the change
matcher看到。当然,这是正确的,但是标准括号在这个例子中起作用的原因是改变可变状态的代码(包含在creating_a_recipe
中)是在作为参数传入expect
时被调用的lambda中。
无论如何,在这种情况下,expect(creating_a_recipe)
或expect { creating_a_recipe }
都可以成功使用,并且您使用的任何一个都可以达到个人偏好。
这个问题是codereview.stackexchange –