TTransmit TTransmit - 2 years ago 150
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, "")
.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 = => "", :ssl => {verify: false})

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

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

assert_requested :get, "", :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 with headers {'Authorization'=>'Bearer fake_oauth_token'} was expected to execute 1 time but it executed 0 times

The following requests were made:

GET 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 Source

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 ( ). 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 { |m| m.respond_to?(:request) }.each do |m|
        headers, body = m.request(self, headers, body)

      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
          :body => body || (@req.file &&,
          :headers => headers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download