gpt4 book ai didi

ruby-on-rails - WebMock.disable_net_connect!不工作

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:31 24 4
gpt4 key购买 nike

我正在尝试编写一个基于 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

请帮助我找出是否缺少某些配置或者我正在做的其他事情。

最佳答案

发现问题出在 VCR 配置中的以下配置:

c.allow_http_connections_when_no_cassette = true

将其转换为 false 解决了问题,因为 VCR 配置覆盖了 webmock 配置,因为我已经定义了 c.hook_into :webmock

关于ruby-on-rails - WebMock.disable_net_connect!不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com