以下代码适用于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
使用assert_requested :get, "http://www.myapi.com/my-endpoint", :headers => {'Authorization' => "Bearer fake_oauth_token"}, :times => 1
并从stub_request中删除标头我从断言中获得以下输出。
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一起使用?
答案 0 :(得分:0)
更新:此问题已在WebMock 2.0.2中修复
以下内容已过期。
WebMock 2.0使用Basic Autorization标头覆盖了Bearer Authorization标头。我在webmock github页面(https://github.com/bblimke/webmock/issues/617)上报告了该问题。在问题得到解决之前,我们正在修补问题,以便注释导致问题的行。
我们在spec_helper中创建了一个文件WebMockHttpClient.rb。这标出了覆盖Bearer Authorization标头的行。
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