I'd like to test my User
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
user.destroy
expect(Project.count).to change(-1)
end
but this gives out an error:
Failure/Error: expect(Project.count).to change(-1)
ArgumentError:
`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 change
isn't the right matcher, is it? Can you please tell me how I could write this test without getting that error?
You can also use shoulda matchers:
it { expect(user).to have_many(:projects).dependent(:destroy) }
https://github.com/thoughtbot/shoulda-matchers
It is the right matcher, but you're not using it the correct way:
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)
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