rack-proxy icon indicating copy to clipboard operation
rack-proxy copied to clipboard

Mock Rack-Proxy RSpec Code

Open jonmchan opened this issue 6 years ago • 1 comments

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.

jonmchan avatar Jan 30 '19 04:01 jonmchan

thx, this is helpful

adrach avatar Dec 23 '19 19:12 adrach