1

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.

Hubro
  • 56,214
  • 69
  • 228
  • 381

1 Answers1

3

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.

Hubro
  • 56,214
  • 69
  • 228
  • 381
  • 1
    A similar way would be to conditionally add the middleware, something like `use MyWebService::Security unless $testing`. That would let you control where in the stack your middleware was added at the cost of having to deal with the flag in your various tests. – matt Nov 14 '14 at 14:17
  • 1
    @matt Yep, but without a way to disable middleware, it would either be enabled or disabled permanently. That could be a problem when testing. For example, most of my tests must be run with security disabled, but the security tests must be run with security enabled. – Hubro Nov 14 '14 at 14:44
  • Frankly, I think this is perfect solution. Middleware is meant to be added through `config.ru`. – Jikku Jose Dec 12 '14 at 02:16