如何阻止RSpec和Capybara的外部连接?

Rav*_*ine 4 ruby testing rspec ruby-on-rails capybara

在我的Rails项目中,我想编写测试非理想条件,如缺乏互联网连接或超时.例如,我正在使用gem来联系API,并且如果我的应用程序和外部API之间存在连接问题,我希望确保正确处理错误.

我已经可以通过使用VCR制作夹具并从"盒式磁带"中删除响应来完成此操作.但是,这有缺点:

  • 它必须手动完成.
  • 如果我和一个团队(我是)一起工作,那么录音带就无法被监控.

如何在我的RSpec测试中简单地创建一个块来阻止外部连接,模拟缺少互联网连接?

stu*_*ujo 5

根据这篇思想机器人文章

https://robots.thoughtbot.com/how-to-stub-external-services-in-tests#disable-all-remote-connections

# spec/spec_helper.rb
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
Run Code Online (Sandbox Code Playgroud)


小智 3

我从未尝试过这样做,但也许您可以使用webmock来阻止所有请求。

before do 
  stub_request(:any, /.*/).to_return(body: "errors", status: 422)
end
Run Code Online (Sandbox Code Playgroud)

有关存根外部服务的更多信息