How do I disable middleware in Sinatra?

446 views Asked by At

I'm making a secured web service using Sinatra. It requires SSL and a security token sent with every request. Therefore I've made a simple middleware that checks each incoming request for a security token, and denies the request if it's missing or invalid.

module MyWebService
  class App < Sinatra::Base
    use MyWebService::Security

    # ...
  end
end

However, this obviously made my large test suite of validation tests fail, because they were written before I added security to the web service.

Is there any way to simply disable the middleware after it has been enabled? That way my entire test suite would still function, and I could test the security middleware separately.

1

There are 1 answers

3
Hubro On BEST ANSWER

I have found a serviceable, though not beautiful, workaround.

Instead of enabling middleware in my application, I enable it in config.ru. So:

module MyWebService
  class App < Sinatra::Base
    use MyWebService::Security   # Remove this line
  end
end

And in config.ru:

require "my_web_service"

app = MyWebService::App
app.use MyWebService::Security

run app

Now all my validation tests pass, and the security middleware is enabled when I start the server.

To test the security middleware, I subclass my app and enable the security middleware in the subclass:

class SecurityMiddlewareValidation < Minitest::Test
  include Rack::Test::Methods

  def app
    Class.new(MyWebService::App) { use MyWebService::Security }
  end

  # ...
end

This way I don't need to disable/enable middleware between tests.