微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在完成测试之前无法连接的 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。