Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stub_request when request body is not predictable

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 => {})
like image 636
Aleksei Matiushkin Avatar asked Sep 23 '15 10:09

Aleksei Matiushkin


1 Answers

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.

like image 62
Alexey Shein Avatar answered Oct 14 '22 07:10

Alexey Shein