代码之家  ›  专栏  ›  技术社区  ›  Aleksei Matiushkin

当请求主体不可预测时stub_request

  •  11
  • Aleksei Matiushkin  · 技术社区  · 9 年前

    我正在用清除http请求 stub_request 此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
    

    谢谢

    更新 存根请求:

    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 => {})
    
    1 回复  |  直到 9 年前
        1
  •  10
  •   Alexey Shein    9 年前

    你需要使用 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 甚至 dynamic evaluating 在…上 request 对象