如何在测试方法中存根 HTTParty 请求?
How to stub a HTTParty request inside a method for testing?
我创建了一个发出 HTTParty get 请求的函数。它引发了我需要测试的自定义错误消息。我尝试在测试中使用 Webmock 存根请求,但它引发了 <Net::OpenTimeout>
。如果 url 是动态构造的,我如何存根获取请求?
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 允许您使用 "wildcard matching" 这样您就可以 stub requests matching a regular expression:
WebMock.stub_request(:get, /example/).to_return(status: 500)
我创建了一个发出 HTTParty get 请求的函数。它引发了我需要测试的自定义错误消息。我尝试在测试中使用 Webmock 存根请求,但它引发了 <Net::OpenTimeout>
。如果 url 是动态构造的,我如何存根获取请求?
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 允许您使用 "wildcard matching" 这样您就可以 stub requests matching a regular expression:
WebMock.stub_request(:get, /example/).to_return(status: 500)