0

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.

everyday_potato
  • 113
  • 1
  • 1
  • 14

1 Answers1

0

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

 expect { api_client.create_implementer('Wayfarer') }.to raise_error(Errno::ECONNREFUSED)
Joel Blum
  • 7,750
  • 10
  • 41
  • 60
  • 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. – everyday_potato May 27 '21 at 15:41
  • It still happens even with the change from my answer? – Joel Blum May 27 '21 at 15:45
  • It does. I put it after `api_client.create_implementer('Wayfarer')`. Is it supposed to go anywhere else? – everyday_potato May 27 '21 at 17:10
  • Not after, you need to replace the line api_client.create_implementer('Wayfarer') with expect { api_client.create_implementer('Wayfarer') }.to raise_error(Errno::ECONNREFUSED) . You never catch the exception thrown there, thats why your spec fails – Joel Blum May 27 '21 at 17:22
  • Out of curiosity, do you know how to redirect in a `Errno::ECONNREFUSED: Connection refused` scenario? – everyday_potato May 27 '21 at 17:50