WebMock.disable_net_connect! not working
Asked Answered
C

1

7

I am trying to write a WebMock based test case to mimic calling a http API. To do so I included webmock/rspec in my spec_helper.rb file and also added WebMock.disable_net_connect!(allow_localhost: true) to disallow the http requests over the web. But when I run a dummy test to check weather the http requests are getting blocked, I can see that the http requests are still been made.

The spec_helper.rb file:

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

Also the dummy test file I have written:

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

Please help me in finding out whether I am missing some configurations or there is something else which I am doing so.

Canister answered 9/7, 2015 at 18:52 Comment(2)
If you comment out the VCR related lines, do you get the same behaviour?Bradberry
@AndyWaite Yes, I am still getting the same behaviour. I also tried disabling the VCR gem in the rails app. But still I am getting the same behaviour.Canister
C
10

Found out the problem was the following configuration in the VCR configs:

c.allow_http_connections_when_no_cassette = true

converting it to false solved the problem as VCR configs were overwriting webmock configs because I had defined c.hook_into :webmock.

Canister answered 10/7, 2015 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.