RSpec test Rollbar called in method where error is raised

737 Views Asked by At

I'm able to test that Rollbar.warning has been called, but when it is called in a method that also raises an error, it fails because an error is raised, and it skips Rollbar.warning.

  context 'unauthorized' do
    before do
      allow(Rollbar).to receive(:warning)
    end

    it 'sends a warning to rollbar' do
      subject.send(:log_and_raise_error)

      expect(Rollbar).to have_received(:warning)
    end
  end

Here's the method I'm testing:

  def log_and_raise_error
    Rollbar.warning(
      "Not authorized error accessing resource #{ResourceID}"
    )

    raise NotAuthorized
  end

But when I run specs, it fails with:

 1) Authorization unauthorized sends a warning to rollbar
     Failure/Error: subject.send(:log_and_raise_error)

     NotAuthorized

Any ideas how I can get around that error raising and still test Rollbar?

1

There are 1 best solutions below

1
On

You can expect the error or rescue it:

expect the error:

    it 'sends a warning to rollbar' do
      expect { subject.send(:log_and_raise_error) }.to raise_error NotAuthorized

      expect(Rollbar).to have_received(:warning)
    end

rescue error:

    it 'sends a warning to rollbar' do
      subject.send(:log_and_raise_error) rescue NotAuthorized

      expect(Rollbar).to have_received(:warning)
    end

or

    it 'sends a warning to rollbar' do
      begin
        subject.send(:log_and_raise_error)
      rescue NotAuthorized
      # noop
      end
      expect(Rollbar).to have_received(:warning)
    end