当请求主体不可预测时,stub_request

Ale*_*kin 7 rspec ruby-on-rails stubbing

我用一个http请求来存根stub_request.这个http请求基本上是一个松弛的通知,它包含一些随机字符串(例如时间戳).

所以,我不能只重复使用代码片段,rspec向我吐口水,因为每次执行时身体都不同.有没有可能用例如模式存根请求,或者我被困在例如Slack#ping

干的代码,jic:

突变

class MyMutation < Mutations::Command
  def run
    slack.ping "#{rand (1..1000)}"
  end
end
Run Code Online (Sandbox Code Playgroud)

规范

describe MyMutation do
  # ??? stub_request ???
  it 'succeeded' do
    expect(MyMutation.new.run.outcome).to be_success
  end
end
Run Code Online (Sandbox Code Playgroud)

谢谢.

UPD存根请求:

stub_request(:post, "https://hooks.slack.com/services/SECRETS").
  with(:body => {"payload"=>"{SLACK_RELATED_PROPS,\"text\":\"MY_RANDOM_HERE\"}"},
       :headers => {'Accept'=>'*/*', MORE_HEADERS}).
  to_return(:status => 200, :body => "", :headers => {})
Run Code Online (Sandbox Code Playgroud)

Ale*_*ein 5

您需要使用部分哈希匹配

stub_request(:post, "https://hooks.slack.com/services/SECRETS").
  with(:body => hash_including("payload"=>"{SLACK_RELATED_PROPS}"),
       :headers => {'Accept'=>'*/*', MORE_HEADERS}).
  to_return(:status => 200, :body => "", :headers => {})
Run Code Online (Sandbox Code Playgroud)

我还建议提供SLACK_RELATED_PROPS为哈希,而不是json编码的字符串。只需从您真正关心的地方选择一些值,然后剥离其他所有内容,例如您随机生成的值。

您可以在文档中查看更多功能,例如正则表达式匹配,甚至可以对对象进行动态评估request

  • FWIW 给未来的读者:请记住, hash_include 不处理嵌套哈希的部分匹配(仅精确匹配),但您可以通过执行 `:body =&gt; hash_include({ a: 123, b: hash_include({ c: ' string' , d: 'string', e: 'string' }) }),` 另请参阅:https://github.com/bblimke/webmock/pull/416 (2认同)