[ ruby ] VCR : Record your test suite’s HTTP interactions and replay them during future test runs

 

Basic Example

setup

VCR.configure do |config|
config.cassette_library_dir = "fixtures/vcr_cassettes"  # fixtures/vcr_cassettes
config.hook_into :webmock
end

use

require 'rubygems'
require 'test/unit'
require 'vcr'

class VCRTest < Test::Unit::TestCase
def test_example_dot_com
VCR.use_cassette("synopsis") do # synopsis.yml
response = Net::HTTP.get_response(URI('http://www.iana.org/domains/reserved'))
assert_match /Example domains/, response.body
end
end
end

 

1st run

VCR will record the HTTP request to fixtures/vcr_cassettes/synopsis.yml. ( You can use a different cassette library directory (e.g., test/vcr_cassettes) )

2nd run

Run it again, and VCR will replay the response from iana.org when the HTTP request is made.

This test is now

  • fast (no real HTTP requests are made anymore)
  • deterministic (the test will continue to pass, even if you are offline, or iana.org goes down for maintenance)
  • accurate (the response will contain the same headers and body you get from a real request).

Another example

VCR.use_cassette('whatever') do
expect do
post :create, post_params
end.to change(Model, :count).by(1)
end

ref : https://github.com/vcr/vcr

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s