TTransmit TTransmit - 6 months ago 30
Ruby Question

stub_request with Bearer Authorisation header not working in webmock 2

The following code works webmock 1.20.4 but not with 2.0.1

stub_request(:get, "http://www.myapi.com/my-endpoint")
.with(headers: {'Authorization' => "Bearer fake_oauth_token"})
.to_return(:body => mock_response)


This is the code I am stubbing.

def get_stuff(oauth_token)
faraday = Faraday.new(:url => "http://www.myapi.com/my-endpoint", :ssl => {verify: false})

response = faraday.get do |req|
req.options[:timeout] = 10
req.headers['Authorization'] = "Bearer #{oauth_token}"
end

if response.status == 200
response.body
else
{error: "failed"}.to_json
end
end


Using
assert_requested :get, "http://www.myapi.com/my-endpoint", :headers => {'Authorization' => "Bearer fake_oauth_token"}, :times => 1
and removing the headers from stub_request I get the following output from the assert.

Failure/Error: assert_requested :get, "#{Conf.graphql[:host]}?query=#{graphql_user_details_query}", :headers => headers, :times => 1

The request GET http://www.myapi.com/my-endpoint with headers {'Authorization'=>'Bearer fake_oauth_token'} was expected to execute 1 time but it executed 0 times

The following requests were made:

GET http://www.myapi.com/my-endpoint with headers {'Accept-Encoding'=>'gzip, compressed', 'Authorization'=>'Basic QmVhcmVyIGZha2Vfb2F1dGhfdG9rZW4=', 'User-Agent'=>'Faraday v0.9.2'} was made 1 time


Is there a way to make the stub_request code work with webmock 2?

Answer

UPDATE: This issue was fixed in WebMock 2.0.2

The following is now out of date.

WebMock 2.0 was overwriting the Bearer Authorization header with a Basic Autorization header. I have reported the issue on the webmock github page ( https://github.com/bblimke/webmock/issues/617 ). Until the issue is resolved, we are monkey patching to comment out the lines that cause the issue.

We created a file WebMockHttpClient.rb that we require in our spec_helper. This comments out the lines that overwrite the Bearer Authorization header.

require 'em-http-request'

module EventMachine
  class WebMockHttpClient

    def build_request_signature
      headers, body = @req.headers, @req.body

      @conn.middleware.select { |m| m.respond_to?(:request) }.each do |m|
        headers, body = m.request(self, headers, body)
      end

      method = @req.method
      uri = @req.uri.clone
      query = @req.query

      uri.query = encode_query(@req.uri, query).slice(/\?(.*)/, 1)

      body = form_encode_body(body) if body.is_a?(Hash)

      headers = @req.headers

      # if headers['authorization']
      #   headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(headers.delete('authorization'))
      # end

      WebMock::RequestSignature.new(
          method.downcase.to_sym,
          uri.to_s,
          :body => body || (@req.file && File.read(@req.file)),
          :headers => headers
      )
    end

  end
end
Comments