我创建了一个发出 HTTParty get 请求的函数。它引发了我需要测试的自定义错误消息。我试图在测试中使用 Webmock stub 请求,但它引发了 <Net::OpenTimeout>
.如果 url 是动态构造的,我如何 stub get 请求?
def function(a , b)
# some logic , dynamic url constructed
response = HTTParty.get(url, headers: {"Content-Type" =>
"application/json"})
if response.code != 200
raise CustomError.new <<~EOF
Error while fetching job details.
Response code: #{response.code}
Response body: #{response.body}
EOF
end
JSON.parse(response.body)
为了测试
def test_function
WebMock.stub_request(:get, url).with(:headers => {'Content-
Type'=>'application/json'}).to_return(:status => 500)
# HTTParty.stub(get: fake_response)
err = assert_raises CustumError do
c.function(a , b)
end
最佳答案
WebMock 允许您使用“通配符匹配”,以便您可以 stub requests matching a regular expression :
WebMock.stub_request(:get, /example/).to_return(status: 500)
关于ruby - 如何在测试方法中 stub HTTParty 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943535/