连接失败的 Webmock 测试在完成测试之前失败
Webmock test for failure to connect fails before finishing test
我已测试连接错误:
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)
我已测试连接错误:
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)