12

I am stubbing an http request with stub_request. This http request is basically a slack notification, that contains some random string (e.g. a timestamp.)

So, I can not just reuse the snippet, rspec spits out to me, because body differs on every execution. Is there any possibility to stub a request with, say, pattern, or I am stuck to hook e.g. the Slack#ping?

The dried code, jic:

mutation

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

spec

describe MyMutation do
  # ??? stub_request ???
  it 'succeeded' do
    expect(MyMutation.new.run.outcome).to be_success
  end
end

Thanks.

UPD stub request:

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 => {})
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160

1 Answers1

11

You need to use partial hash matching:

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 => {})

I'd also recommend to provide SLACK_RELATED_PROPS as a hash, not as a json-encoded string. Just choose some values from there that you really care about, and strip everything else, like your random-generated value.

You can view more features in docs, such as regex matching or even dynamic evaluating on request object.

Alexey Shein
  • 7,342
  • 1
  • 25
  • 38
  • 2
    FWIW to future readers: remember that hash_including doesn't handle partial matching of nested hashes (only exact matches), but you can solve it by doing `:body => hash_including({ a: 123, b: hash_including({ c: 'string' , d: 'string', e: 'string' }) }),` See also: https://github.com/bblimke/webmock/pull/416 – Magne Feb 23 '17 at 14:21