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

时间:2018-12-27 10:31:14

标签: ruby minitest httparty webmock

我创建了一个发出HTTParty get请求的函数。它提出了我需要测试的自定义错误消息。我尝试在测试中使用Webmock对请求进行存根,但是它引发了<Net::OpenTimeout>。如果网址是动态构建的,我该如何存根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

1 个答案:

答案 0 :(得分:1)

WebMock允许您使用“通配符匹配”,因此您可以stub requests matching a regular expression

WebMock.stub_request(:get, /example/).to_return(status: 500)