Testing Faraday with VCR and MiniTest in a Rails App

Our team is currently working on a rails app that makes multiple calls to multiple apis. The results of those calls need to be tested, but since we are working with things like Github contribution history, the data will change daily. Also, we want to avoid hitting our rate limits by hitting them multiple times, every time we run the testing suite. 

VCR is a gem that pulls in the data from an http request, and stores it for you. It's super helpful, but it has gone through a lot of versions and most of the tutorials and blog posts that I found were outdated!.

Here are two things I learned

If you are using Capybara::Rails::TestCase - VCR will NOT notify you in the console if it doesn't have a cassette for the call you're making. It will just silently fail your test. 

There is a bug with earlier VCR versions, Faraday and Ruby 2.0.0 and above! You must specify gem 'vcr', '2.4.0' in the gemfile and delete all preexisting cassettes-- otherwise it'll just record empty cassettes.

Supposedly fixtures can mess with your cassettes, so I was advised to move the cassettes folder out of test. Not sure if this was actually a problem - but I did this to be safe.

So here is how I set up VCR

Gemfile :

group :development, :test do
  #additional gems above (obviously)
  gem 'vcr', '2.4.0 

test_helper.rb :

require 'faraday'
require 'vcr'

VCR.configure do |c|
  c.cassette_library_dir = './cassettes'
  c.hook_into :faraday

Create a cassettes folder

(I put my cassettes folder in the main directory, because of concerns about it messing with the fixtures.)

Wrap any section of your tests that involve an html call :

VCR.use_cassette('make up a name of the cassette here') do
  #the test code

Here is an example from our tests :

def test_get_error_for_invalid_user
  VCR.use_cassette('invalid_api_cassette') do
    user = "adamasdfcueahg89"
    ai = ApiRequest.new(user, "github")
    assert_equal "adamasdfcueahg89 is not a valid username with github", ai.get_streak

Once I got over the odd glitches, I found the testing was pretty helpful. 

Check out the documentation for some other ways to wrap tests. Supposedly there is a method by which you can wrap the entire test or testing suite - but I had limited success with doing that. I'll give it a try when it comes time to run the refactor tractor :)


The VCR Gem on Github

API Documentation