Search code examples
ruby-on-railsrubyrspecsentry

Rspec testing Sentry's Raven capture_exception


Let's say I have this snippet of code...

  Raven.capture_exception(error, {
    extra: {
      error_message: message
    }
  })
end

I have tried to use expect(Raven).to receive(:capture_exception).with(...) and no matter how I slice this, I can not seem to bind an expect to Raven so I can verify it was sent the logging communications. It keeps telling me capture_exception is not defined. I have tried both expect and expect_any_instance_of with no luck. For now, I have skipped this, but I know there is a way. Thoughts?


Solution

  • Not completely sure of what do you want to test exactly, but this works for me:

    class Test
      def self.test
        begin
          1 / 0
        rescue => exception
          Raven.capture_exception(exception)
        end
      end
    end
    

    In a test, I can setup an RSpec spy: https://relishapp.com/rspec/rspec-mocks/docs/basics/spies

    it 'calls raven capture_exception' do
      allow(Raven).to receive(:capture_exception) # Setup the spy
    
      Test.test # Call the function that uses Raven.capture_exception
    
      expect(Raven).to have_received(:capture_exception) # Check that the spy was called
    end