[英]How to test dependent: :destroy with RSpec?
我想测试我的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
但这给出了一个错误:
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.
所以我认为change
不是正确的匹配器,是吗? 你能告诉我如何编写这个测试而不会出现那个错误吗?
您还可以使用 shoulda 匹配器:
it { expect(user).to have_many(:projects).dependent(:destroy) }
这是正确的匹配器,但您没有以正确的方式使用它:
正确的方法是
expect { user.destroy }.to change { Project.count }
这只是断言数值变化,但没有指定变化多少。 为此,将调用链接到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.