我正在使用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头-我如何存根,使他们被忽略?
Web mock默认进行部分匹配。在您的示例中,:user_agent
键是一个与字符串'User-Agent'
不匹配的符号。转换为字符串应该可以工作:
'User-Agent'=>'Custom user agent'
可以使用hash_include:
stub_request(:get, "https://myhost.com/api").
with(:headers => hash_including({:user_agent => 'Custom user agent'})).
to_return(:status => 200, :body => '')