【问题标题】:http client with custom params具有自定义参数的 http 客户端
【发布时间】:2018-03-08 14:30:26
【问题描述】:

我使用此代码发出网络请求:

request = HTTPClient.new()
request.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE 
request.set_auth(url, terminal['api_login'], terminal['api_password'])        
response = request.post(url, request_body, {"Content-Type" => "application/xml", "cache-control" => "no-cache"}).body

但是当我尝试使用存根请求实现 rspec 时,添加了两个参数,它们在每个测试环境中每次都不同:

stub_request(:post, "http://www.example.com/").
         with(:headers => {'Accept'=>'*/*', 'Cache-Control'=>'no-cache', 'Content-Type'=>'application/xml', 'Date'=>'Thu, 08 Mar 2018 14:20:55 GMT', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.2.2 (2015-04-13))'}).
         to_return(:status => 200, :body => "", :headers => {})

如何配置 http 客户端不发送 Date 并让 User-Agent 发送像“Ruby”这样简单的东西?

是否可以配置这些参数?

【问题讨论】:

    标签: ruby stub


    【解决方案1】:

    有一个伟大的宝石来处理这种情况,它被称为Timecophttps://github.com/travisjeffery/timecop。基本上,您可以冻结时间,或移动到特定日期。在您的情况下,我认为您只需要冻结时间,以便您可以在存根标头中设置任意日期。

    Timecop.freeze
      stub_request(:post, "http://www.example.com/").
         with(:headers => {'Accept'=>'*/*', 'Cache-Control'=>'no-cache', 'Content-Type'=>'application/xml', 'Date'=> Time.now, 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.2.2 (2015-04-13))'}).
         to_return(:status => 200, :body => "", :headers => {})
      # the rest of your test here
    end
    

    此外,您可以通过省略标头并为 url 使用正则表达式来简化存根,例如:

    stub_request(:post, /.example.*\/).and_return(:status => 200, :body => "", :headers => {})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-21
      • 2017-01-19
      • 2022-08-18
      • 1970-01-01
      • 2011-03-01
      • 2022-06-23
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多