ruby-on-railsruby-on-rails-6webmock

Webmock test for failure to connect fails before finishing test


I have test to for connection error:

context 'unsuccessful API request' do
  it 'responds like 500 if connection error is raised' do
    http_stub = instance_double(Net::HTTP)
    allow(Net::HTTP).to receive(:new).and_return(http_stub)
    allow(http_stub).to receive(:request).and_raise(Errno::ECONNREFUSED)

    api_client = ApiClient.new

    api_client.create_implementer('Wayfarer')

    expect(api_client.response_status).to eq(500)
    expect(api_client.response_body).to eq({ issue' => [{ 'details' => { 'text' => 'Connection error' }}]})
  end
end

And when I run it, it fails like it's supposed to but fails in the method instead of in the test so the test for the failure fails:

Failure/Error: response = http.request(request)
     
Errno::ECONNREFUSED:
  Connection refused

Which is the correct error but it's failing in the method:

  def http_request(request, uri)
    http = Net::HTTP.new(uri.host, uri.port)

    response = http.request(request)
    @response_status = response.code.to_i

    if response_successful?
      @response_body = parsed_response(response)
    else
      @response_body = response.body rescue Errno::ECONNREFUSED
      connection_error
    end
  end

The issue is it's stopping in the middle of the http_request method at the line for response = http.request(request). It doesn't follow through with the error handling.

If I put a binding.pry after that line it isn't reached and the method just bails.


Solution

  • You need to expect the error to be raised in your spec

     expect { api_client.create_implementer('Wayfarer') }.to raise_error(Errno::ECONNREFUSED)