如何在测试方法中存根 HTTParty 请求?

spa*_*tar 4 ruby minitest httparty webmock

我创建了一个发出 HTTParty get 请求的函数。它会引发我需要测试的自定义错误消息。我尝试在测试中使用 Webmock 来存根请求,但它引发了<Net::OpenTimeout>. 如果 url 是动态构造的,我如何存根 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)
Run Code Online (Sandbox Code Playgroud)

为了测试

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
Run Code Online (Sandbox Code Playgroud)

cod*_*mev 5

WebMock 允许您使用“通配符匹配”,以便您可以存根与正则表达式匹配的请求

WebMock.stub_request(:get, /example/).to_return(status: 500)
Run Code Online (Sandbox Code Playgroud)