【问题标题】:How to stub requests on domain or after method?如何在域或之后的方法上存根请求?
【发布时间】:2016-05-23 07:00:34
【问题描述】:
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_uidSecureRandom.urlsafe_base64 随机代码。我也在 config.before(:each) 中存根。

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

【问题讨论】:

  • 您将此添加到哪个规范文件中?

标签: ruby-on-rails ruby rspec webmock


【解决方案1】:

我看到两个选项:

  • 存根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 has a very large number of other ways to match requests

【讨论】:

  • 您好,感谢您的回答!我不知道我可以存根 SecureRandom。无论如何,我设法使用正则表达式 stub_request(:post, %r{https://api.3rdpartysmsprovider.com}). to_return(:status => 200, :body => "01", :headers => {}) 来解决它,它基本上是 stub_request(:post, "api.3rdpartysmsprovider.com"). to_return(status: 200, body: "01", headers: {}),除了出于某种原因将它作为字符串存根对我不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多