1

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

4

2 回答 2

1

您可以使用 hash_include :


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

于 2013-05-13T09:01:52.900 回答
1

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

'User-Agent'=>'Custom user agent'
于 2018-03-19T10:00:01.927 回答