Webmock 不响应 stub_request

标签 webmock

在 features/support/webmock.rb 中,我有

stub_request(:get, /(http\:\/\/catalog\.viglink\.com\/vigcatalog\/products\.xml\?include_identifiers=true&key=.*&keyword_upc=628586348097&results_per_page=20)/).
with(:headers => {'Accept'=>'*/*; q=0.5, application/xml', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => File.open('spec/support/628586348097.txt'))

我有两个应该调用此 stub 的 cucumber 场景。在一种情况下, stub 被识别,并且测试通过。在另一种情况下,我收到以下信息:

Real HTTP connections are disabled. Unregistered request: GET http://catalog.viglink.com/vigcatalog/products.xml?include_identifiers=true&key=key&keyword_upc=628586348097&results_per_page=20 with headers {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'User-Agent'=>'Ruby'}

You can stub this request with the following snippet:

stub_request(:get, "http://catalog.viglink.com/vigcatalog/products.xml?include_identifiers=true&key=key&keyword_upc=628586348097&results_per_page=20").
with(:headers => {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})

关于为什么 webmock 不能识别 stub 请求有什么建议吗?

最佳答案

在 webmock.rb 文件中,确保将 stub_requests 放在 Before block 中。否则,您需要将它们包含在您的步骤中...

require 'webmock/cucumber'

Before do
  WebMock.disable_net_connect! #A precaution to avoid webmock making real http calls

  stub_request(:get, /.*url*/).to_return(:body => File.new("#{::Rails.root}/support/webmock/listing.json")
end

关于Webmock 不响应 stub_request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19835157/

相关文章:

ruby-on-rails - Webmock:如何伪造 gzipped 响应?

ruby-on-rails - 如何正确复制 Webmock stub 的 HTTParty 请求响应的响应正文

ruby - 在 webmock 中对同一个端点的多次调用具有不同的结果?

ruby-on-rails - WebMock stub_request 不工作

ruby-on-rails - 即使在指定磁带后,VCR 仍显示 "no cassette in use"

ruby - 如何使用 webmock 伪造对 Capybara/poltergeist 的响应?

ruby - WebMock 模拟失败的 API(没有互联网,超时++)

ruby-on-rails - VCR 与 webmock 阻止我的 rspec

ruby-on-rails - 使用WebMock Rails模拟证书

ruby-on-rails - 如果尚未调用,则强制 Webmock stub_request 在测试结束时引发