Convert Figma logo to code with AI

vcr logovcr

Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.

5,817
502
5,817
85

Top Related Projects

3,963

Library for stubbing and setting expectations on HTTP requests in Ruby.

10,203

Record, Replay, and Stub HTTP Interactions.

12,708

HTTP server mocking and expectations library for Node.js

Quick Overview

VCR is a Ruby library that records your test suite's HTTP interactions and replays them during future test runs for fast, deterministic, and accurate tests. It helps in isolating your tests from external services and reduces the dependency on network connectivity during testing.

Pros

  • Speeds up test suites by eliminating actual HTTP requests after initial recording
  • Ensures consistent test results by replaying the same responses
  • Allows tests to run without an internet connection once interactions are recorded
  • Supports various HTTP libraries and adapters

Cons

  • Initial setup and configuration can be complex for newcomers
  • Recorded cassettes may need frequent updates if the external API changes
  • Can potentially mask real issues with external services if not managed properly
  • May increase the size of your project due to stored cassettes

Code Examples

Recording and replaying HTTP interactions:

require 'vcr'

VCR.use_cassette('example_cassette') do
  response = Net::HTTP.get_response(URI('https://api.example.com/users'))
  puts response.body
end

Configuring VCR:

VCR.configure do |config|
  config.cassette_library_dir = 'spec/vcr_cassettes'
  config.hook_into :webmock
  config.filter_sensitive_data('<API_KEY>') { ENV['API_KEY'] }
end

Using VCR with RSpec:

RSpec.describe 'API Client' do
  it 'fetches user data' do
    VCR.use_cassette('user_data') do
      response = APIClient.get_user(1)
      expect(response).to include('name' => 'John Doe')
    end
  end
end

Getting Started

  1. Add VCR to your Gemfile:

    gem 'vcr'
    gem 'webmock' # or another supported HTTP library
    
  2. Configure VCR in your test setup (e.g., spec/spec_helper.rb):

    require 'vcr'
    
    VCR.configure do |config|
      config.cassette_library_dir = 'spec/vcr_cassettes'
      config.hook_into :webmock
    end
    
  3. Use VCR in your tests:

    RSpec.describe 'MyAPI' do
      it 'fetches data' do
        VCR.use_cassette('my_api_request') do
          response = MyAPI.fetch_data
          expect(response).to be_success
        end
      end
    end
    

Competitor Comparisons

3,963

Library for stubbing and setting expectations on HTTP requests in Ruby.

Pros of WebMock

  • More flexible for stubbing and mocking HTTP requests
  • Allows fine-grained control over request matching and response generation
  • Supports a wider range of HTTP libraries and frameworks

Cons of WebMock

  • Requires more manual setup and maintenance of stubs
  • Can be more complex to use for simple scenarios
  • Doesn't automatically record and playback real HTTP interactions

Code Comparison

WebMock example:

stub_request(:get, "https://api.example.com/users")
  .to_return(status: 200, body: '{"users": []}', headers: {'Content-Type' => 'application/json'})

VCR example:

VCR.use_cassette("users_list") do
  response = Net::HTTP.get_response(URI('https://api.example.com/users'))
end

Summary

WebMock is a powerful tool for stubbing and mocking HTTP requests, offering great flexibility and control. It's ideal for complex testing scenarios where precise request matching and response generation are needed. However, it requires more manual setup compared to VCR.

VCR, on the other hand, excels at recording and replaying real HTTP interactions, making it easier to set up and maintain tests for existing APIs. It's particularly useful for integration testing and scenarios where you want to capture actual API responses.

The choice between WebMock and VCR depends on your specific testing needs, with WebMock being better for fine-grained control and VCR for ease of use with real API interactions.

10,203

Record, Replay, and Stub HTTP Interactions.

Pros of Pollyjs

  • Built for JavaScript, making it ideal for Node.js and browser-based applications
  • Supports multiple adapters (fetch, XHR, node-http) out of the box
  • Offers a user-friendly UI for managing and editing recorded sessions

Cons of Pollyjs

  • Less mature compared to VCR, with fewer community contributions
  • Limited language support (primarily JavaScript)
  • May require more setup and configuration for complex scenarios

Code Comparison

VCR (Ruby):

VCR.use_cassette("example") do
  response = Net::HTTP.get_response(URI('http://example.com'))
end

Pollyjs (JavaScript):

await polly.record(() => {
  return fetch('http://example.com');
});

Both libraries aim to simplify HTTP interaction recording and playback for testing purposes. VCR is more established and widely used in the Ruby ecosystem, while Pollyjs is tailored for JavaScript applications. VCR offers broader language support through ports, whereas Pollyjs provides a more modern approach with its UI and adapter system. The choice between them often depends on the primary programming language and specific project requirements.

12,708

HTTP server mocking and expectations library for Node.js

Pros of Nock

  • Lightweight and focused specifically on HTTP mocking
  • Simpler setup and usage, especially for JavaScript/Node.js projects
  • Built-in support for dynamic responses and conditional behavior

Cons of Nock

  • Limited to HTTP mocking, less versatile than VCR
  • Requires manual definition of mocks, which can be time-consuming
  • Less suitable for recording and replaying real API interactions

Code Comparison

VCR (Ruby):

VCR.use_cassette("example") do
  response = Net::HTTP.get_response(URI('http://example.com'))
end

Nock (JavaScript):

nock('http://example.com')
  .get('/')
  .reply(200, 'Hello World');

const response = await fetch('http://example.com');

Key Differences

  • VCR focuses on recording and replaying HTTP interactions, while Nock is primarily for defining mock responses
  • VCR supports multiple HTTP libraries and protocols, whereas Nock is specific to Node.js HTTP requests
  • VCR's cassettes allow for easier sharing of recorded interactions, while Nock requires manual mock definitions

Use Cases

  • Choose VCR for projects requiring realistic API simulation or cross-language support
  • Opt for Nock in JavaScript/Node.js projects with simple HTTP mocking needs or when fine-grained control over mock responses is necessary

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

vcr

CI status GitHub tag (latest SemVer) Version OpenCollective OpenCollective

Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.

Help Wanted

We're looking for more maintainers. If you'd like to help maintain a well-used gem please spend some time reviewing pull requests, issues, or participating in discussions.

Usage

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

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

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

Run this test once, and VCR will record the HTTP request to fixtures/vcr_cassettes/synopsis.yml. 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) and accurate (the response will contain the same headers and body you get from a real request). You can use a different cassette library directory (e.g., "test/vcr_cassettes").

NOTE: To avoid storing any sensitive information in cassettes, check out Filter Sensitive Data in the documentation.

Rails and Minitest: Do not use 'test/fixtures' as the directory if you're using Rails and Minitest (Rails will instead transitively load any files in that directory as models).

Features

  • Automatically records and replays your HTTP interactions with minimal setup/configuration code.
  • Supports and works with the HTTP stubbing facilities of multiple libraries. Currently, the following are supported:
  • Supports multiple HTTP libraries:
  • Request matching is configurable based on HTTP method, URI, host, path, body and headers, or you can easily implement a custom request matcher to handle any need.
  • The same request can receive different responses in different tests--just use different cassettes.
  • The recorded requests and responses are stored on disk in a serialization format of your choice (currently YAML and JSON are built in, and you can easily implement your own custom serializer) and can easily be inspected and edited.
  • Dynamic responses are supported using ERB.
  • Optionally re-records cassettes on a configurable regular interval to keep them fresh and current.
  • Disables all HTTP requests that you don't explicitly allow.
  • Simple Cucumber integration is provided using tags.
  • Includes convenient RSpec macros and integration with RSpec 2 metadata.
  • Known to work well with many popular Ruby libraries including RSpec 1 & 2, Cucumber, Test::Unit, Capybara, Mechanize, Rest Client and HTTParty.
  • Includes Rack and Faraday middleware.
  • Supports filtering sensitive data from the response body

The docs come in two flavors:

  • The usage docs contain example-based documentation (VCR's Cucumber suite, in fact). It's a good place to look when you are first getting started with VCR, or if you want to see an example of how to use a feature.
  • The rubydoc.info docs contain API documentation. The API docs contain detailed info about all of VCR's public API.
  • See the CHANGELOG doc for info about what's new and changed.

There is also a Railscast (from 2011), which will get you up and running in no-time http://railscasts.com/episodes/291-testing-with-vcr.

Release Policy

VCR follows the principles of semantic versioning. The API documentation defines VCR's public API. Patch level releases contain only bug fixes. Minor releases contain backward-compatible new features. Major new releases contain backwards-incompatible changes to the public API.

Ruby Interpreter Compatibility

VCR versions 6.x are tested on the following ruby interpreters:

  • MRI 3.1
  • MRI 3.0
  • MRI 2.7
  • MRI 2.6

VCR 6.0.0 is the last version supporting >= 2.4. Upcoming releases will only explicitly support >= 2.6.

Development

  • Source hosted on GitHub.
  • Direct questions and discussions on GitHub Issues.
  • Report bugs/issues on GitHub Issues.
  • Pull requests are very welcome! Please include spec and/or feature coverage for every patch, and create a topic branch for every separate change you make.
  • See the Contributing guide for instructions on running the specs and features.
  • Code quality metrics are checked by Code Climate.
  • Documentation is generated with YARD (cheat sheet). To generate while developing:
yard server --reload

Ports in Other Languages

Related Projects

  • Mr. Video (Rails engine for managing VCR cassettes and episodes)

Similar Libraries in Ruby

Credits

Thanks also to the following people who have contributed patches or helpful suggestions:

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]