11

我有简单的测试用例:

it "is removed when associated board is deleted" do
  link = FactoryGirl.create(:link)
  link.board.destroy
  expect(Link.find(link.id)).to raise_error ActiveRecord::RecordNotFound
end

它失败并输出:

1) Link is removed when associated board is deleted
   Failure/Error: expect(Link.find(link.id)).to raise_error ActiveRecord::RecordNotFound
   ActiveRecord::RecordNotFound:
     Couldn't find Link with id=1
   # ./spec/models/link_spec.rb:47:in `block (2 levels) in <top (required)>'

知道为什么吗?

4

1 回答 1

27

要捕获错误,您需要将代码包装在一个块中。您的代码正在Link.find(link.id)预期错误的范围内执行。适当的测试:

it "is removed when associated board is deleted" do
  link = FactoryGirl.create(:link)
  link.board.destroy
  expect { Link.find(link.id) }.to raise_error ActiveRecord::RecordNotFound
end
于 2013-06-20T12:07:19.173 回答