3
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 并在我们的数据库中创建它的日志的服务类编写规范。我正在尝试存根此请求,但@text.sms_uid它是一个SecureRandom.urlsafe_base64随机代码。我也在打架config.before(:each)

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

4

1 回答 1

2

我看到两个选项:

  • 存根SecureRandom.urlsafe_base64返回已知字符串并在以下情况下使用该已知字符串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 有非常多的其他方式来匹配请求

于 2016-05-26T16:44:26.030 回答