Possible Duplicate:
Is it possible for RSpec to expect change in two tables?
it "should create a new Recipe" do
expect { click_button submit }.to change(Recipe, :count).by(1)
end
This allows me to check that the 'Recipe' model has one more entry, but I'd like to also check that the 'Ingredient' model has one more entry. The expect block can only be executed once, since the form is submitted already.
I know I could just make another 'it' block, but I feel that there must be a DRYer way.
I would propose DRYing it up by redefining the test subject (and using stabby lambdas for fun):
describe "recipe creation" do
subject { -> { click_button submit } }
it { should change(Recipe, :count).by(1) }
it { should change(Ingredient, :count).by(1) }
end
Update: Although it may look less DRY, these days I would probably still keep on using the expect
syntax, since it's recommended and I'm generally moving away from should
, but perhaps make some minor changes for spec readability:
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
Note: you may see in the RSpec documentation for the change
matcher that expect
uses curly brackets. This is, of course, correct, but the reason that standard parenthesis work in this example is that the code that changes mutable state (contained in creating_a_recipe
) is in a lambda that gets called when passed into expect
as a parameter.
Regardless, in this case either expect(creating_a_recipe)
or expect { creating_a_recipe }
can be used successfully, and whichever one you use is up to personal preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With