【问题标题】:Using webmock to stub partial headers使用 webmock 存根部分标头
【发布时间】:2013-05-12 21:17:19
【问题描述】:

我正在使用 webmock 创建测试。我想测试是否设置了特定的标头字段,但我不关心其他标头字段。当我使用这个时:

stub_request(:get, "https://myhost.com/api").
  with(:headers => {:user_agent => 'Custom user agent'}).
  to_return(:status => 200, :body => '')

我收到一个错误,因为我没有对所有标题进行存根:

Unregistered request: GET https://myhost.com/api with headers {'Accept'=>'application/json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Custom user agent'}

You can stub this request with the following snippet:

stub_request(:get, "https://myhost.com/api").
  with(:headers => {'Accept'=>'application/json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent'=>'Custom user agent'}).
  to_return(:status => 200, :body => "", :headers => {})

我不关心 Accept 和 Accept-Encoding 标头 - 我如何存根以使它们被忽略?

【问题讨论】:

    标签: ruby rspec webmock


    【解决方案1】:

    您可以使用 hash_include :

    
         stub_request(:get, "@987654321@").
           with(:headers => hash_including({:user_agent => 'Custom user agent'})).
           to_return(:status => 200, :body => '')
        

    【讨论】:

    • 当我使用 hash_include 时出现此错误:github.com/bblimke/webmock/issues/276。它对你有用吗?
    • 是的,它对我来说很好用。没有出现过这样的错误,抱歉。
    • 部分匹配的头部不需要写hash_including
    • 我也得到了github.com/bblimke/webmock/issues/276 中描述的错误,不幸的是,Webmock 的默认部分匹配功能与hash_including 的用例不匹配,hash_including 可以单独匹配键而不是键值对。我希望这个解决方案能够奏效,但根据我的经验,它不会。
    【解决方案2】:

    Web mock 默认情况下会进行部分匹配。在您的情况下,:user_agent 键是一个与字符串 'User-Agent' 不匹配的符号。转换为字符串应该可以工作:

    'User-Agent'=>'Custom user agent'
    

    【讨论】:

      猜你喜欢
      • 2013-02-28
      • 2014-02-17
      • 2014-06-03
      • 2015-04-29
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      相关资源
      最近更新 更多