您只需要世界上最简单的 Rack 应用程序:
let(:app) { lambda {|env| [200, {'Content-Type' => 'text/plain'}, ['OK']]} }
此外,你的中间件的构造函数应该接收一个应用程序作为它的第一个参数而不是一个哈希,所以它应该是:
subject { MyMiddleWare.new(app) }
但是,您的测试很可能需要确定中间件对请求的影响。因此,您可能会编写一个稍微复杂的机架应用程序来监视您的中间件。
class MockRackApp
attr_reader :request_body
def initialize
@request_headers = {}
end
def call(env)
@env = env
@request_body = env['rack.input'].read
[200, {'Content-Type' => 'text/plain'}, ['OK']]
end
def [](key)
@env[key]
end
end
然后你可能想要使用 Rack::MockRequest 来实际发送请求。就像是:
describe MyMiddleWare do
let(:app) { MockRackApp.new }
subject { described_class.new(app) }
context "when called with a POST request" do
let(:request) { Rack::MockRequest.new(subject) }
before(:each) do
request.post("/some/path", input: post_data, 'CONTENT_TYPE' => 'text/plain')
end
context "with some particular data" do
let(:post_data) { "String or IO post data" }
it "passes the request through unchanged" do
expect(app['CONTENT_TYPE']).to eq('text/plain')
expect(app['CONTENT_LENGTH'].to_i).to eq(post_data.length)
expect(app.request_body).to eq(post_data)
end
end
end
end