如何使用80端口和webmock注册请求存根?

时间:2015-04-14 03:07:14

标签: ruby-on-rails ruby rspec port webmock

我正在使用webmock来存根并在Ruby中设置对HTTP请求的期望。我也在使用rspec

这是我的spec/feature/***.rb代码:

require 'webmock/rspec'
require 'net/http'
require 'uri'

# ...
it 'Request third-part API' do
  stub_request(:get, "http://third_part_api_path/api/param=value")
  Net::HTTP.get("http://third_part_api_path", "/api/param=100")
  expect(WebMock).to have_requested(:get, "http://third_part_api_path/api/param=100")
end

但在运行我的rspec测试代码后,错误是:

Failure/Error: Net::HTTP.get(@uri, "/api/param=100”)
 WebMock::NetConnectNotAllowedError:
   Real HTTP connections are disabled. Unregistered request: GET http://http//third_part_api_path:80/api/param=100 with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'}

   You can stub this request with the following snippet:

   stub_request(:get, "http://http//third_part_api_path:80/api/param=100”).
     with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Ruby'}).
     to_return(:status => 200, :body => "", :headers => {})

   registered request stubs:

   stub_request(:get, "http://http//third_part_api_path/api/param=100”)

   ============================================================

1 个答案:

答案 0 :(得分:0)

您不需要协议:http:// Net::HTTP.get的部分网址 - 只是裸网址

例如

Net::HTTP.get("third_part_api_path", "/api/param=100")

Net::HTTP docs