stub_request 当请求正文不可预测时
stub_request when request body is not predictable
我正在用 stub_request
存根一个 http 请求。这个 http 请求基本上是一个松弛通知,其中包含一些随机字符串(例如时间戳)
所以,我不能只重复使用代码段,rspec
向我吐槽,因为每次执行时正文都不同。有没有可能用模式来存根请求,或者我被困住了,例如Slack#ping
?
干货代码,jic:
突变
class MyMutation < Mutations::Command
def run
slack.ping "#{rand (1..1000)}"
end
end
规格
describe MyMutation do
# ??? stub_request ???
it 'succeeded' do
expect(MyMutation.new.run.outcome).to be_success
end
end
谢谢。
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 => {})
您需要使用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 => {})
我还建议提供 SLACK_RELATED_PROPS
作为散列,而不是 json 编码的字符串。只需从那里选择一些您真正关心的值,然后去掉其他所有值,例如随机生成的值。
您可以在文档中查看更多功能,例如 regex matching or even dynamic evaluating 在 request
对象上。
我正在用 stub_request
存根一个 http 请求。这个 http 请求基本上是一个松弛通知,其中包含一些随机字符串(例如时间戳)
所以,我不能只重复使用代码段,rspec
向我吐槽,因为每次执行时正文都不同。有没有可能用模式来存根请求,或者我被困住了,例如Slack#ping
?
干货代码,jic:
突变
class MyMutation < Mutations::Command
def run
slack.ping "#{rand (1..1000)}"
end
end
规格
describe MyMutation do
# ??? stub_request ???
it 'succeeded' do
expect(MyMutation.new.run.outcome).to be_success
end
end
谢谢。
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 => {})
您需要使用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 => {})
我还建议提供 SLACK_RELATED_PROPS
作为散列,而不是 json 编码的字符串。只需从那里选择一些您真正关心的值,然后去掉其他所有值,例如随机生成的值。
您可以在文档中查看更多功能,例如 regex matching or even dynamic evaluating 在 request
对象上。