Xeen Xeen - 8 months ago 88
Ruby Question

How to test dependent: :destroy with RSpec?

I'd like to test my

models association
has_many :projects, dependent: :destroy
and have gone this far for now:

it "destroys dependent projects" do
user = FactoryGirl.build(:user)
project = FactoryGirl.build(:project)

user.projects << project

expect(Project.count).to change(-1)

but this gives out an error:

Failure/Error: expect(Project.count).to change(-1)
`change` requires either an object and message (`change(obj, :msg)`) or a block (`change { }`). You passed an object but no message.

so I presume that
isn't the right matcher, is it? Can you please tell me how I could write this test without getting that error?


It is the right matcher, but you're not using it the correct way:

  • expect needs to receive a block containing the action to perform (in your case deleting the user)
  • change needs to receive a block that produces the numerical value that is expected to change (it can also receive an object and a symbol indicating that rspec should call the named method)

The correct way is

expect { user.destroy }.to change { Project.count }

This just asserts that the numerical value changes, but does not specify by how much. To do that, chain a call to by:

expect { user.destroy }.to change { Project.count }.by(-1)