Search code examples
ruby-on-railsrubyrspecportwebmock

How to register a request stub using 80 port with webmock?


I am using webmock to stub and set expectations on HTTP requests in Ruby. Also I am using rspec.

Here is my spec/feature/***.rb's code:

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

But after I run my rspec test code, the error was:

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”)

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

Solution

  • you don't need the protocol: http:// part of the URL for the Net::HTTP.get - just the bare URL

    eg

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

    Net::HTTP docs