1

Using RSpec with Rails 6.0.0 I'm specifying that a record needs to be deleted after an acion is performed. To do this I call reload on the object and expect it to raise anActiveRecord::RecordNotFound error

Ironically the test fails because of an ActiveRecord::RecordNotFound error. What's with that?

Here's the relevant part of my spec:

  context 'when deleting a notice' do
    let(:notice) { FactoryBot.create(:program_notice) }
    let(:request_proto) { Sil::Rev79::Id.new(uuid: notice.id) }
    subject { run_rpc(:DeleteNotice, request_proto) }

    context 'as admin user' do
      include_context 'admin user'

      it "deletes the notice" do
        expect(subject).to be_a Google::Protobuf::Empty
        expect(notice.reload).to raise_error ActiveRecord::RecordNotFound
      end

    end
  end

and this is the failure message:

3) ProgramsController when deleting a notice as admin user deletes the notice Failure/Error: expect(notice.reload).to raise_error ActiveRecord::RecordNotFound

 ActiveRecord::RecordNotFound:
   Couldn't find ProgramNotice with 'id'=47e2d9c1-a009-4b9c-a7a5-2279ae74d74d
 # ./spec/rpc/programs_controller_spec.rb:360:in `block (4 levels) in <main>'

line 360 in the test file is that second expect statement.

Toby 1 Kenobi
  • 4,717
  • 2
  • 29
  • 43
  • 3
    Try `expect { notice.reload }.to raise_error ActiveRecord::RecordNotFound`. Read the [doc](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher) here. Read this [answer](https://stackoverflow.com/a/19962317/2767755) to know why block is important in this case. – Arup Rakshit Jul 29 '19 at 16:50

1 Answers1

4

The second expectation needs to set up with a block, not as a parameter:

expect { notice.reload }.to raise_error ActiveRecord::RecordNotFound

eugen
  • 8,916
  • 11
  • 57
  • 65