ncr / rack-proxy

A request/response rewriting HTTP proxy. A Rack app.
MIT License
269 stars 94 forks source link

Mock Rack-Proxy RSpec Code #79

Open jonmchan opened 5 years ago

jonmchan commented 5 years ago

Not sure where this belongs - maybe we can open up a wiki?

For those interested in mocking out rack-proxy for a test, the following code has worked very well for me.

  before(:all) do
    WebMock.disable!
  end

  after(:all) do
    WebMock.enable!
  end

  def stub_rack_proxy(status_code, status_msg, headers, body)
    streaming_response = Rack::HttpStreamingResponse.new(nil,'test', '443')
    expect(streaming_response).to receive(:headers) { headers }
    expect(streaming_response).to receive(:body) { body }
    http_response = Net::HTTPResponse.new('1.0', status_code, status_msg)
    expect(streaming_response).to receive(:response) {  http_response }
    expect(Rack::HttpStreamingResponse).to receive(:new) do |request, host, port|
      yield(request, host, port)
      streaming_response
    end
  end

  # test example:
  it 'makes a call to xyz.site' do
    stub_rack_proxy(200, 'OK', { }, '{"status":"ok"}') do |request, host, port|
      expect(host).to eql('xyz.site')
      expect(port).to eql('443')

      expect(request.to_hash).to eql( { "Headers": "to remote site goes here" } )
      expect(request.path).to eql('/remote/path/')
    end
  end

Useful if you want to test code in your custom proxy, but you don't want the request to be actually made. Since rack-proxy isn't compatible with WebMock, this is the workaround I have come up with.

Note: This only works for streaming: true, you'd have to stub out stuff in Net::HTTP if you set streaming: false.

adrach commented 4 years ago

thx, this is helpful