Skip to content

Easy Integration of Minitest::Spec and VCR

I’m a big fan of MiniTest. I use it for basically all of my testing in Ruby. I’ve also started to use VCR to help with stubbing and recording HTTP requests during tests. In a nutshell, VCR lets hit the actual resource on the first run. VCR then records the results and replays them back on subsequent test runs. It really helps to speed up tests and isolate externals.

Recently, I had to integrate VCR with MiniTest::Spec. MiniTest by default runs tests in random order. Additionally, there is no after(:all) hook available in MiniTest. When integrating MiniTest with VCR, tests which would have otherwise been unaffected by order may now produce false failures due to VCR.

This is when I came up with a rather simple solution to have each test run in isolation and have their own specific cassette. At my top level describe block for each test file, I have a before block that sets up a VCR cassette for each expectation. Here’s the code for this solution (and a gist):

describe "Something" do
  before do
    # __name__ defined in MiniTest::Unit::TestCase
    VCR.insert_cassette __name__

  after do

Now every single it or specify block that makes one or more HTTP requests will generate and use it’s own cassette. Granted, this solution is somewhat verbose in the amount of cassettes that are generated. I feel however, this is a reasonable trade off for its sheer simplicity!

Update: I added this solution and some more general information about MiniTest to VCR’s wiki.