Marcin Doliwa
Marcin Doliwa

Reputation: 3659

Expect to raise_error and test fails because it raises this error

I have simple test case:

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

And it fails with output:

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)>'

Any idea why ?

Upvotes: 11

Views: 2656

Answers (1)

samuil
samuil

Reputation: 5081

To catch error you need to wrap code in a block. Your code is executing Link.find(link.id) in the scope that is not expecting error. Proper test:

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

Upvotes: 27

Related Questions