0

以下代码适用于 webmock 1.20.4 但不适用于 2.0.1

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

这是我正在存根的代码。

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

从 stub_request使用assert_requested :get, "http://www.myapi.com/my-endpoint", :headers => {'Authorization' => "Bearer fake_oauth_token"}, :times => 1和删除标头我从断言中获得以下输出。

   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

有没有办法让 stub_request 代码与 webmock 2 一起工作?

4

1 回答 1

1

更新:此问题已在 WebMock 2.0.2 中修复

以下内容现已过时。

WebMock 2.0 使用 Basic Autorization 标头覆盖 Bearer Authorization 标头。我已经在 webmock github 页面 ( https://github.com/bblimke/webmock/issues/617 ) 上报告了这个问题。在问题解决之前,我们会进行猴子补丁以注释掉导致问题的行。

我们创建了一个文件 WebMockHttpClient.rb,我们在 spec_helper 中需要它。这会注释掉覆盖承载授权标头的行。

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
于 2016-05-10T05:39:09.387 回答