Search code examples
rubytestingsinatraracksentry

How to test if some specific rack middleware is being used?


To be more particular, I'm talking about sentry-raven and sinatra here. I saw examples testing sinatra applications, or middlewares. But I didn't see ones testing if some particular middleware is present. Or should I be testing behavior, not configuration (or how should I call it)?


Solution

  • With help from ruby-raven guys, we've got this:

    ENV['RACK_ENV'] = 'test'
    
    # the app: start
    
    require 'sinatra'
    require 'sentry-raven'
    
    Raven.configure(true) do |config|
      config.dsn = '...'
    end
    
    use Raven::Rack
    
    get '/' do
      'Hello, world!'
    end
    
    # the app: end
    
    require 'rspec'
    require 'rack/test'
    
    Raven.configure do |config|
      logger = ::Logger.new(STDOUT)
      logger.level = ::Logger::WARN
      config.logger = logger
    end
    
    describe 'app' do
      include Rack::Test::Methods
    
      def app
        @app || Sinatra::Application
      end
    
      class TestRavenError < StandardError; end
    
      it 'sends errors to sentry' do
        @app = Class.new Sinatra::Application do
          get '/' do
            raise TestRavenError
          end
        end
        allow(Raven.client).to receive(:send).and_return(true)
        begin
          get '/'
        rescue TestRavenError
        end
        expect(Raven.client).to have_received(:send)
      end
    end
    

    Or if raven sending requests is in the way (when tests fail because of raven sending requests, and not because of the underlying error), one can disable them:

    Raven.configure(true) do |config|
      config.should_send = Proc.new { false }
    end
    

    And mock Raven.send_or_skip instead:

    ...
    allow(Raven).to receive(:send_or_skip).and_return(true)
    begin
      get '/'
    rescue TestRavenError
    end
    expect(Raven).to have_received(:send_or_skip)
    ...