Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for ActiveRecord::RecordNotFound

My application is propagating a ActiveRecord::RecordNotFound to the controller when a model can't retrieve a record.

Here is the DB query:

def self.select_intro_verse
  offset = rand(IntroVerse.count)
  IntroVerse.select('line_one', 'line_two', 'line_three', 'line_four', 'line_five').offset(offset).first!.as_json
end

first! raises a ActiveRecord::RecordNotFound if no record is found, and I am able to rescue it and render an appropriate template in my controller.

This is the expected behavior so I would like to have a test for it in my specs. I wrote:

context "verses missing in database" do
  it "raises an exception" do
    expect(VerseSelector.select_intro_verse).to raise_exception
  end
end

When I run rspec:

1) VerseSelector verses missing in database raises an exception Failure/Error: expect(VerseSelector.select_intro_verse).to raise_exception ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound

To me the test fails even though the exception is raised! How can I make my test pass?

like image 717
fkoessler Avatar asked Jul 10 '14 09:07

fkoessler


1 Answers

Look in documentation for rspec-expectations#expecting-errors this:

expect(VerseSelector.select_intro_verse).to raise_exception

should be except syntax for exception must be lambda or proc:

expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)
like image 200
Philidor Avatar answered Oct 23 '22 09:10

Philidor