使用webmock来存根部分标题

时间:2013-05-12 21:17:20

标签: ruby rspec webmock

我正在使用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标头 - 如何存根以便忽略它们?

2 个答案:

答案 0 :(得分:0)

你可以使用hash_including:     


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

答案 1 :(得分:0)

Web模拟仅默认部分匹配。但在你的情况下,user_agent键是一个符号会导致不匹配。它必须是一个字符串。

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