How can I block external connections with RSpec & Capybara?

僤鯓⒐⒋嵵緔 提交于 2020-05-26 13:40:31

问题


With my Rails project, I would like to write tests non-ideal conditions such as lack of internet connection or timeouts. For example, I am using a gem to contact an API and would like to make sure that I handle the error correctly if there is a connection issue between my app and the external API.

I can do this already by making a fixture with VCR and removing the response from the "cassette". However, this has drawbacks:

  • It has to be done manually.
  • The cassettes can not be gitignored if I am working with a team(which I am).

How can I simply create a block in my RSpec tests that will prevent external connections, simulating the lack of an internet connection?


回答1:


I've never tried to do this, but perhaps you could use webmock to stub out all requests.

before do 
  stub_request(:any, /.*/).to_return(body: "errors", status: 422)
end

More info on stubbing external services.




回答2:


Per this thought-bot article

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)


来源:https://stackoverflow.com/questions/26130939/how-can-i-block-external-connections-with-rspec-capybara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!