Intermediate TDD in Rails : Speed Up Tests using VCR

Objective


Learn how to use VCR to speed up tests.

Discussion


The gateway test hits the real servers, the test suite will become slow as it grows. So, let's use VCR gem to speed up the tests.

Steps


Step 1

Add the following gems to Gemfile.

gem 'vcr'
gem 'webmock'

Run bundle.

Step 2

The gem automatically creates the spec/fixtures/vcr_cassettes/create_customer.yml file when it hits the Stripe servers the first time.

$rspec spec/gateway/stripe_gateway_spec.rb 
.*

Pending: (Failures listed here are expected and do not affect your suite's status)

  1) StripeGateway should subscribe a customer to a given plan
     # Not yet implemented
     # ./spec/gateway/stripe_gateway_spec.rb:27


Finished in 0.90104 seconds (files took 3.11 seconds to load)
2 examples, 0 failures, 1 pending

It took 0.9 seconds to run one test.

Step 3

Run the same test again. It takes much less time, since it does not hit the network anymore. It loads the data from the fixture file. On my system the time it took to run it the second time was 0.32598 seconds.

Summary


In this lesson we used VCR gem to record the network interactions so that tests do not go over the network, thereby speeding up our test suite.


Related Articles


Create your own user feedback survey