简体   繁体   English

如何测试依赖::destroy with RSpec?

[英]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:这是正确的匹配器,但您没有以正确的方式使用它:

  • expect needs to receive a block containing the action to perform (in your case deleting the user) expect 需要接收一个包含要执行的操作的块(在您的情况下删除用户)
  • 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) change 需要接收一个产生预期改变的数值的块(它也可以接收一个对象和一个符号,指示 rspec 应该调用命名方法)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM