Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 985
Marcin Doliwa Avatar asked Jun 20 '13 11:06

Marcin Doliwa


People also ask

What is let in Ruby?

Use let to define a memoized helper method. The value will be cached across multiple calls in the same example but not across examples. Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked.

What is subject in RSpec?

Summary: RSpec's subject is a special variable that refers to the object being tested. Expectations can be set on it implicitly, which supports one-line examples. It is clear to the reader in some idiomatic cases, but is otherwise hard to understand and should be avoided.


1 Answers

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
like image 61
samuil Avatar answered Oct 23 '22 23:10

samuil