针对连接失败的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 { api_client.create_implementer('Wayfarer') }.to raise_error(Errno::ECONNREFUSED)

相关内容

  • 没有找到相关文章

最新更新