在完成测试之前无法连接的 Webmock 测试失败

问题描述

我测试了连接错误:

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

当我运行它时,它会像预期的那样失败,但是在方法中而不是在测试中失败,因此失败的测试失败了:

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

哪个是正确的错误,但在方法中失败了:

  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

问题是它在 http_request 行的 response = http.request(request) 方法中间停止。它没有执行错误处理。

如果我在该行后面放了一个 binding.pry,它不会到达并且该方法只是保释。

解决方法

您需要在您的规范中expect the error to be raised

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...