我正在尝试编写一个基于WebMock
的测试用例来模仿调用http API。
为此,我在webmock/rspec
文件中添加了spec_helper.rb
,并添加了WebMock.disable_net_connect!(allow_localhost: true)
以禁止通过网络发送http请求。
但是,当我运行虚拟测试以检查天气时,http请求被阻止,我可以看到仍然发出了http请求。
spec_helper.rb文件:
ENV["RAILS_ENV"] ||= 'test'
require 'rubygems'
require File.expand_path("../../config/environment", __FILE__)
require 'authlogic/test_case'
include Authlogic::TestCase
require 'rspec/rails'
require 'rspec/autorun'
require 'rspec/mocks'
require 'capybara/rspec'
require 'capybara/rails'
require "paperclip/matchers"
require 'vcr'
require 'webmock/rspec'
WebMock.disable_net_connect!
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.mock_with :rspec
config.use_transactional_fixtures = false
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include Paperclip::Shoulda::Matchers
config.include FactoryGirl::Syntax::Methods
config.infer_base_class_for_anonymous_controllers = false
config.include Rails.application.routes.url_helpers
config.include Capybara::DSL
config.render_views
config.filter_run focus: true
config.run_all_when_everything_filtered = true
end
VCR.configure do |c|
c.cassette_library_dir = 'spec/vcr_cassettes'
c.hook_into :webmock
c.allow_http_connections_when_no_cassette = true
end
ActiveSupport::Dependencies.clear
我写的虚拟测试文件:
require 'spec_helper'
describe 'External request' do
it 'queries FactoryGirl contributors on GitHub' do
uri = URI('https://api.github.com/repos/thoughtbot/factory_girl/contributors')
response = Net::HTTP.get(uri)
expect(response).to be_an_instance_of(String)
end
end
请帮我弄清楚我是否遗漏了一些配置,或者我还有其他的东西。
答案 0 :(得分:4)
发现问题是VCR
配置中的以下配置:
c.allow_http_connections_when_no_cassette = true
将其转换为false
解决了问题,因为VCR
配置覆盖webmock
配置因为我已定义c.hook_into :webmock
。