Usage with MiniTest

Casper Hollingberry edited this page Jul 31, 2014 · 7 revisions

To use VCR with with MiniTest, you can insert and eject individual cassettes within before and after calls.

describe 'Something' do
  before do
    VCR.insert_cassette 'something'
  end

  after do
    VCR.eject_cassette
  end

  it "makes an HTTP request" do
     # ...
  end
end

It's possible to easily integrate VCR with MiniTest dynamically. This technique will produce a cassette for each test that makes one more HTTP requests. The functionality is achieved by using the name method provided by MiniTest::Test.

describe 'SomethingElse' do
  before do
    VCR.insert_cassette name

    # make HTTP request in before
  end

  after do
    # make HTTP request in after

    VCR.eject_cassette
  end

  it "makes first HTTP request" do
    # ...
  end

  it "makes some more HTTP requests" do
    # ...
  end
end

This will dynamically produce two cassettes, test_0001_makes_first_http_request and test_0002_makes_some_more_http_requests respectively. The HTTP requests that are made in the before and after block will also be included within these cassettes. Only tests that actually make HTTP requests will produce a cassette file with this solution.

To automate the cassette management and naming you can use the minitest-vcr gem.

Add this line to your application's Gemfile:

gem "minitest-vcr"

And then execute:

$ bundle

Or install it yourself as:

$ gem install minitest-vcr

Add this line before your tests load (test_helper.rb, spec_helper.rb, etc.)

MinitestVcr::Spec.configure!

Now in your test file all you have to add is a symbol as the second argument in the describe or it.

describe 'Something', :vcr do
  describe "something else do
    it "makes an HTTP request" do # You could also put it here
      # ...
    end
    
    it "makes another request" do
      # ...
    end
  end
end 

This will create a file structure something like this:

|-- app_name
|  |-- test/
|    |-- cassettes/
|      |-- Something/
|        |-- something_else/
|        `-- makes_an_http_request.yml
|        `-- makes_another_request.yml

Since MiniTest will run tests in a random order, tests which would have otherwise been unaffected by order may now produce false failures due to VCR. This technique is especially useful if this is the case with your code since each test will have it's own isolated cassette.

This solution may be somewhat verbose in the amount of cassettes that are generated, but it's simplicity and ease may be a worthwhile trade off!