B Seven
B Seven

Reputation: 45943

How to test the request (not response) of a Rack middleware?

I can see how to test the response of a rack middleware, but how to test the request?

That is, how to test when the middleware changes the request going to the app?

Working in RSpec and Sinatra.

Upvotes: 1

Views: 969

Answers (2)

ian
ian

Reputation: 12251

@Denis's answer would work, but I'd personally prefer an alternative, which is to put the middleware in a bare Rack app (be it Sinatra or whatever) and just pass the request on as the response and test that. It's how most Rack middleware is specced. That, and unit testing the internals of the middleware.

For example, it's what I've done here with a fork of Rack Clicky


Edit: testing middleware separately from the main app.

require 'lib/rack/mymiddelware.rb'
require 'sinatra/base'

describe "My Middleware" do
  let(:app) {
    Sinatra.new do
      use MyMiddleware
      get('/') { request.env.inspect }
    end
  }
  let(:expected) { "Something you expect" }
  before do
    get "/"
  end
  subject { last_response.body }
  it { should == expected }
end

Upvotes: 2

Denis de Bernardy
Denis de Bernardy

Reputation: 78443

I presume you're meaning testing whether it's changing env...

A middleware goes something like:

class Foo
  def initialize(app)
    @app = app
  end

  def call(env)
    # do stuff with env ...
    status, headers, response = @app.call(env)

    # do stuff with status, headers and response
    [status, headers, response]
  end
end

You could initialize it with a bogus app (or a lambda, for that matter) that returns a dummy response after doing some tests:

class FooTester
  attr_accessor :env

  def call(env)
    # check that env == @env and whatever else you need here
    [200, {}, '']
  end
end

Upvotes: 2

Related Questions