Search code examples
rubyrspecwebmock

rspec webmock to_raise error not raising error


I have the following code snippet and test

class Service
  def self.status(base_uri = 'localhost', basic_auth = {})
    base_uri = "#{ base_uri }/status"
    response = HTTParty.get(base_uri, basic_auth: basic_auth)
  rescue StandardError => e
    binding.pry
    raise "Error occured code: #{ response.code } msg: #{ e.message }"
  end
end
it 'should return error msg if url is not valid' do
  bad_url = "http://bar_url.com"
  expected = 'Error occured'
  stub_request(:get, bad_url).
            with(headers: {'Authorization'=>'Basic YWRtaW46YWRtaW4='}).
            to_raise(StandardError)

  expect { Service.status(bad_url, { username: @username, password: @password }) }.to raise_error(/#{ expected }/) 
end 

This code is based on the documentation.
As a result rspec always raises an exception:

expected /Error occured/, got #<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: GET h...rization'=>'Basic YWRtaW46YWRtaW4='})

Can anyone help me figure out what I should change to get a StandardError as a result?


Solution

  • Since the service calls "#{ base_uri }/status" which is http://bar_url.com/status but the stub_request is declared with http://bar_url.com only, the Net::HTTP.Get looks for match with this instead of http://bar_url/status.
    This is the reason why there is no error raising in the test.