ruby-on-railsrspecvcr

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


Solution

  • 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.