如何对域或方法后的请求存根?

How to stub requests on domain or after method?

config.before(:each) do
  stub_request(:post, "https://api.3rdpartysmsprovider.com/send.php?body=This%20is%20a%20test%20message&destination=60123456789&dlr='1'&output=json&password=0000000&reference=#{@text.sms_uid}&sender=silver&username=0000000").
    to_return(:status => 200, :body => "01", :headers => {})
end

我目前正在为发送 SMS 并在我们的数据库中创建日志的服务 class 编写规范。我试图存根这个请求,但是 @text.sms_uid 是一个 SecureRandom.urlsafe_base64 随机代码。我也在 config.before(:each).

存根

因此,我无法在 stub_request 中指定 sms_uid,因为调用存根后会生成随机 sms_uid。这导致测试每次都失败。有没有办法在请求生成代码后(换句话说,在它通过特定方法之后)存根,或者有没有办法存根所有通过域“https://api.silverstreet.com”的请求?

我看到两个选项:

  • 存根 SecureRandom.urlsafe_base64 到 return 一个已知字符串,并在 stub_request:

    时使用该已知字符串
    config.before(:each) do
      known_string = "known-string"
      allow(SecureRandom).to receive(:known_string) { known_string }
      stub_request(:post, "https://api.3rdpartysmsprovider.com/send.php?body=This%20is%20a%20test%20message&destination=60123456789&dlr='1'&output=json&password=0000000&reference=#{known_string}&sender=silver&username=0000000").
        to_return(status: 200, body: "01", headers: {})
    end
    

    如果在您的应用程序的其他地方使用了 SecureRandom.urlsafe_base64,您只需要在生成此请求的规范中对其进行存根。

  • 是的,您可以将任何 POST 添加到该主机名

    stub_request(:post, "api.3rdpartysmsprovider.com").
      to_return(status: 200, body: "01", headers: {})
    

    甚至是对该主机名的任何类型的请求

    stub_request(:any, "api.3rdpartysmsprovider.com").
      to_return(status: 200, body: "01", headers: {})
    

    webmock has a very large number of other ways to match requests.