Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec, expect to change with multiple values [duplicate]

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.

like image 615
David Frey Avatar asked Dec 20 '12 05:12

David Frey


1 Answers

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.

like image 173
Paul Fioravanti Avatar answered Oct 10 '22 23:10

Paul Fioravanti