http客户端与自定义参数

时间:2018-03-08 14:30:27

标签: ruby stub

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

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时,会添加两个params,每次在每个测试环境中都不同:

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客户端不发送DateUser-Agent发送简单的内容,例如' Ruby'?

是否可以配置这些参数?

1 个答案:

答案 0 :(得分:0)

有一个伟大的宝石来处理这种情况,它被称为Timecop https://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

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

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