如何测试依赖::用RSpec破坏?

时间:2015-02-09 09:43:34

标签: ruby-on-rails ruby unit-testing testing 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不是正确的匹配者,是吗?你能否告诉我如何在没有出现错误的情况下编写此测试?

5 个答案:

答案 0 :(得分:32)

您也可以使用shoulda matchers:

it { expect(user).to have_many(:projects).dependent(:destroy) }

https://github.com/thoughtbot/shoulda-matchers

答案 1 :(得分:26)

这是正确的匹配器,但你没有以正确的方式使用它:

  • 期望需要接收包含要执行的操作的块(在您删除用户的情况下)
  • change需要接收一个块,该块产生预期会改变的数值(它也可以接收一个对象和一个表示rspec应该调用命名方法的符号)

正确的方法是

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

这只是断言数值会改变,但不会指定多少。为此,请将来电链接到by

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

答案 2 :(得分:3)

这应该有效:

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

答案 3 :(得分:1)

您应该测试删除实际项目。

mmacosx-version-min=10.5

答案 4 :(得分:0)

这应该有效:

it { is_expected.to have_many(:projects).dependent(:destroy) }