Use*_*159 18 rack rspec ruby-on-rails rack-middleware
我写了一些Rack-Middleware,现在我正试着用Rspec测试它.但所有Rack-Middleware都使用'app'参数进行实例化,该参数代表Rails应用程序本身.你们怎么在Rspec嘲笑这个?
例如,
 describe MyMiddleWare do
    let(:app) { # How do I mock a Rails app object here? }
    subject { MyMiddleWare.new(app: app) }
    it 'should blah blah blah' do
       # a bunch of tests go here
    end
 end
Rit*_*hie 24
你只需要世界上最简单的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
| 归档时间: | 
 | 
| 查看次数: | 8015 次 | 
| 最近记录: |