Test for ActiveRecord::RecordNotFound
activerecord, rspec, ruby, ruby-on-rails, ruby-on-rails-4
Solution
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)
Problem
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?