[英]How to test dependent: :destroy with RSpec?
I'd like to test my User
models association has_many :projects, dependent: :destroy
and have gone this far for now:我想测试我的
User
模型关联has_many :projects, dependent: :destroy
现在已经走了这么远:
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?所以我认为
change
不是正确的匹配器,是吗? Can you please tell me how I could write this test without getting that error?你能告诉我如何编写这个测试而不会出现那个错误吗?
You can also use shoulda matchers:您还可以使用 shoulda 匹配器:
it { expect(user).to have_many(:projects).dependent(:destroy) }
https://github.com/thoughtbot/shoulda-matchers https://github.com/thoughtbot/should-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
:为此,将调用链接到
by
:
expect { user.destroy }.to change { Project.count }.by(-1)
这应该有效:
expect { user.destroy }.to change { Project.count }.by(-1)
您应该测试是否删除了实际项目。
expect(Project.all).not_to include project
这应该有效:
it { is_expected.to have_many(:projects).dependent(:destroy) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.