marcantonio
marcantonio

Reputation: 1069

Restricting VCR to specs

Is there a way to make VCR active only when called via rspec in a Rails app? It works great for my tests, but I don't want it to intercept requests when outside of those tests.

I get Real HTTP connections are disabled if I use a client to connect to the my app and the app is calling an external web service.

Thanks, Marc

Upvotes: 2

Views: 1309

Answers (2)

marcantonio
marcantonio

Reputation: 1069

I finally got this work as desired with Rails. I was able to disable VCR (WebMock, actually, which is the backend I chose for VCR) except when I'm running rspec. For background, I initially followed the instructions here when setting up VCR.

First, I create config/initializers/webmock.rb:

# Disable WebMock globally so it doesn't interfere with calls outside of the specs.
WebMock.disable!

Then I added the following around VCR.use_cassette() (in my case this is in spec_helper.rb:

config.around(:each, :vcr) do |example|
  name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
  options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
+ # Only enable WebMock for the specs.  Don't interfere with calls outside of this.
+ WebMock.enable!
  VCR.use_cassette(name, options) { example.call }
+ WebMock.disable!
end

Hope that helps someone.

Upvotes: 1

user4203675
user4203675

Reputation:

make sure that your VCR gem is set in the proper group

# Gemfile
group :test do
  ......
  gem 'vcr'
end

take a look at http://natashatherobot.com/vcr-gem-rails-rspec/ for more help.

Upvotes: 2

Related Questions