使用webmock和黄瓜

问题描述

我正在使用webmock,它不适用于黄瓜测试 在我的Gemfile中
  gem \'vcr\'
  gem \'webmock\'
在我的features / support.env.rb中,
require \'webmock/cucumber\'
WebMock.allow_net_connect!
当我运行黄瓜测试时,出现此错误。
    Real HTTP connections are disabled. Unregistered request:
 GET http://127.0.0.1:9887/__identify__ with headers
 {\'Accept\'=>\'*/*\',\'Accept-Encoding\'=>\'gzip;q=1.0,deflate;q=0.6,identity;q=0.3\',\'User-Agent\'=>\'Ruby\'}
我做错什么了吗?     

解决方法

首先,如果您使用的是VCR,则无需使用
require \'webmock/cucumber\'
行和
WebMock.allow_net_connect!
行配置webmock。 VCR为您处理任何必要的WebMock配置。 触发错误的请求看起来像是来自Capybara。当您使用一种javascript驱动程序时,capybara使用简单的机架服务器引导您的应用程序,然后轮询特殊的
__identify__
路径,以便它知道启动完成的时间。 VCR包括对忽略localhost请求的支持,以便不会干扰此请求。有趣的文档具有完整的故事,但简短的版本是您需要添加VCR配置,如下所示:
VCR.config do |c|
  c.ignore_localhost = true
end
    ,我没有使用VCR,但遇到了相同的错误。我能够通过添加以下内容解决此问题:
require \'webmock/cucumber\'
WebMock.disable_net_connect!(:allow_localhost => true)
到我的env.rb文件。     ,扩展Myron Marston的答案。如果您需要将本地主机保留在其他位置(例如Rack App),而您可能希望VCR捕获其请求,则需要创建一个自定义匹配器,而不是忽略所有本地主机请求。
require \'vcr\'

VCR.configure do |c|
  c.hook_into :webmock
  c.ignore_localhost = false

  c.ignore_request do |request|
    localhost_has_identify?(request)
  end
end


private
def localhost_has_identify?(request)
  if(request.uri =~ /127.0.0.1:\\d{5}\\/__identify__/)
    true
  else
    false
  end
end
    ,如果同时使用RSpec和Cucumber,则可能需要为WebMock创建两个配置文件(与VCR一起使用时):
# spec/support/webmock.rb
# Config for RSpec
require \'webmock/rspec\'
WebMock.disable_net_connect!(allow_localhost: true)

# features/support/webmock.rb
# Config for Cucumber
require \'webmock/cucumber\'
WebMock.disable_net_connect!(allow_localhost: true)
在这里记录这个文档,以便人们在搜寻
__identify__
时可以找到。错误看起来像...
Real HTTP connections are disabled.
Unregistered request: GET http://127.0.0.1:59005/__identify__ 
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...