Class: VCR::Configuration

Inherits:
Object
  • Object
show all
Includes:
Hooks, Logger::Mixin, VariableArgsBlockCaller
Defined in:
lib/vcr/configuration.rb,
lib/vcr/deprecations.rb

Overview

Stores the VCR configuration.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logger::Mixin

#log, #request_summary, #response_summary

Methods included from VariableArgsBlockCaller

#call_block

Methods included from Hooks

#clear_hooks, #has_hooks_for?, #hooks, included, #invoke_hook

Instance Attribute Details

#allow_http_connections_when_no_cassette?Boolean (writeonly) #allow_http_connections_when_no_cassette=Object (writeonly)

Determines how VCR treats HTTP requests that are made when no VCR cassette is in use. When set to ‘true`, requests made when there is no VCR cassette in use will be allowed. When set to `false` (the default), an Errors::UnhandledHTTPRequestError will be raised for any HTTP request made when there is no cassette in use.

Overloads:

  • #allow_http_connections_when_no_cassette?Boolean

    Returns whether or not HTTP connections are allowed when there is no cassette.

    Returns:

    • (Boolean)

      whether or not HTTP connections are allowed when there is no cassette.

  • #allow_http_connections_when_no_cassette=Object

    Parameters:

    • value (Boolean)

      sets whether or not to allow HTTP connections when there is no cassette.



129
130
131
# File 'lib/vcr/configuration.rb', line 129

def allow_http_connections_when_no_cassette=(value)
  @allow_http_connections_when_no_cassette = value
end

#debug_logger#puts #debug_logger=(logger) ⇒ void

An object to log debug output to.

Examples:

VCR.configure do |c|
  c.debug_logger = $stderr
end
VCR.configure do |c|
  c.debug_logger = File.open('vcr.log', 'w')
end

Overloads:

  • #debug_logger#puts

    Returns the logger.

    Returns:

    • (#puts)

      the logger

  • #debug_logger=(logger) ⇒ void

    This method returns an undefined value.

    Parameters:

    • logger (#puts)

      the logger



440
441
442
# File 'lib/vcr/configuration.rb', line 440

def debug_logger
  @debug_logger
end

#default_cassette_optionsHash #default_cassette_options=(options) ⇒ void

Note:

VCR#insert_cassette for the list of valid options.

Default options to apply to every cassette.

Examples:

VCR.configure do |c|
  c.default_cassette_options = { :record => :new_episodes }
end

Overloads:

  • #default_cassette_optionsHash

    Returns default options to apply to every cassette.

    Returns:

    • (Hash)

      default options to apply to every cassette

  • #default_cassette_options=(options) ⇒ void

    This method returns an undefined value.

    Parameters:

    • options (Hash)

      default options to apply to every cassette



46
47
48
# File 'lib/vcr/configuration.rb', line 46

def default_cassette_options
  @default_cassette_options
end

#loggerObject (readonly)

Logger object that provides logging APIs and helper methods.



454
455
456
# File 'lib/vcr/configuration.rb', line 454

def logger
  @logger
end

#query_parser#call #query_parser=Object

Sets a parser for VCR to use when parsing query strings for request comparisons. The new parser must implement a method ‘call` that returns an object which is both equalivant and consistent when given an HTTP query string of possibly differing value ordering.

  • ‘#== # => Boolean`

The ‘#==` method must return true if both objects represent the same query string.

This defaults to ‘CGI.parse` from the ruby standard library.

Overloads:

  • #query_parser#call

    Returns the current query string parser object.

    Returns:

    • (#call)

      the current query string parser object

  • #query_parser=Object

    Parameters:

    • value (#call)

      sets the query_parser



151
152
153
# File 'lib/vcr/configuration.rb', line 151

def query_parser
  @query_parser
end

#uri_parser#parse #uri_parser=Object

Sets a parser for VCR to use when parsing URIs. The new parser must implement a method ‘parse` that returns an instance of the URI object. This URI object must implement the following interface:

  • ‘scheme # => String`

  • ‘host # => String`

  • ‘port # => Fixnum`

  • ‘path # => String`

  • ‘query # => String`

  • ‘#port=`

  • ‘#query=`

  • ‘#to_s # => String`

  • ‘#== # => Boolean`

The ‘#==` method must return true if both URI objects represent the same URI.

This defaults to ‘URI` from the ruby standard library.

Overloads:

  • #uri_parser#parse

    Returns the current URI parser object.

    Returns:

    • (#parse)

      the current URI parser object

  • #uri_parser=Object

    Parameters:

    • value (#parse)

      sets the uri_parser



177
178
179
# File 'lib/vcr/configuration.rb', line 177

def uri_parser
  @uri_parser
end

Instance Method Details

#after_http_request(*filters) {|request, response| ... } ⇒ Object

Adds a callback that will be called with each HTTP request after it is complete.

Examples:

VCR.configure do |c|
  c.after_http_request(:ignored?) do |request, response|
    puts "Request: #{request.method} #{request.uri}"
    puts "Response: #{response.status.code}"
  end
end

Parameters:

  • filters (optional splat of #to_proc)

    one or more filters to apply. The objects provided will be converted to procs using ‘#to_proc`. If provided, the callback will only be invoked if these procs all return `true`.

Yields:

  • the callback

Yield Parameters:

See Also:



366
367
368
# File 'lib/vcr/configuration.rb', line 366

def after_http_request(*filters)
  super(*filters.map { |f| request_filter_from(f) })
end

#allow_http_connections_when_no_cassette?Boolean

Returns:

  • (Boolean)


131
132
133
# File 'lib/vcr/configuration.rb', line 131

def allow_http_connections_when_no_cassette?
  !!@allow_http_connections_when_no_cassette
end

#around_http_request(*filters) {|request| ... } ⇒ Object

Note:

This method can only be used on ruby interpreters that support fibers (i.e. 1.9+). On 1.8 you can use separate ‘before_http_request` and `after_http_request` hooks.

Note:

You must call ‘request.proceed` or pass the request as a proc on to a method that yields to a block (i.e. `some_method(&request)`).

Adds a callback that will be executed around each HTTP request.

Examples:

VCR.configure do |c|
  c.around_http_request(lambda {|r| r.uri =~ /api.geocoder.com/}) do |request|
    # extract an address like "1700 E Pine St, Seattle, WA"
    # from a query like "address=1700+E+Pine+St%2C+Seattle%2C+WA"
    address = CGI.unescape(URI(request.uri).query.split('=').last)
    VCR.use_cassette("geocoding/#{address}", &request)
  end
end

Parameters:

  • filters (optional splat of #to_proc)

    one or more filters to apply. The objects provided will be converted to procs using ‘#to_proc`. If provided, the callback will only be invoked if these procs all return `true`.

Yields:

  • the callback

Yield Parameters:

Raises:

See Also:



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/vcr/configuration.rb', line 395

def around_http_request(*filters, &block)
  unless VCR.fibers_available?
    raise Errors::NotSupportedError.new \
      "VCR::Configuration#around_http_request requires fibers, " +
      "which are not available on your ruby intepreter."
  end

  fibers = {}
  fiber_errors = {}
  hook_allowed, hook_declaration = false, caller.first
  before_http_request(*filters) do |request|
    hook_allowed = true
    start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block)
  end

  after_http_request(lambda { hook_allowed }) do |request, response|
    fiber = fibers.delete(Thread.current)
    resume_fiber(fiber, fiber_errors, response, hook_declaration)
  end
end

#before_playback(tag = nil) {|interaction, cassette| ... } ⇒ Object

Adds a callback that will be called before a previously recorded HTTP interaction is loaded for playback.

Examples:

VCR.configure do |c|
  # Don't playback transient 5xx errors
  c.before_playback do |interaction|
    interaction.ignore! if interaction.response.status.code >= 500
  end

  # Change a response header for playback
  c.before_playback(:twilio) do |interaction|
    interaction.response.headers['X-Foo-Bar'] = 'Bazz'
  end
end

Parameters:

  • tag ((optional) Symbol) (defaults to: nil)

    Used to apply this hook to only cassettes that match the given tag.

Yields:

  • the callback

Yield Parameters:

See Also:



325
326
327
# File 'lib/vcr/configuration.rb', line 325

def before_playback(tag = nil, &block)
  super(tag_filter_from(tag), &block)
end

#before_record(tag = nil) {|interaction, cassette| ... } ⇒ Object

Adds a callback that will be called before the recorded HTTP interactions are serialized and written to disk.

Examples:

VCR.configure do |c|
  # Don't record transient 5xx errors
  c.before_record do |interaction|
    interaction.ignore! if interaction.response.status.code >= 500
  end

  # Modify the response body for cassettes tagged with :twilio
  c.before_record(:twilio) do |interaction|
    interaction.response.body.downcase!
  end
end

Parameters:

  • tag ((optional) Symbol) (defaults to: nil)

    Used to apply this hook to only cassettes that match the given tag.

Yields:

  • the callback

Yield Parameters:

See Also:



297
298
299
# File 'lib/vcr/configuration.rb', line 297

def before_record(tag = nil, &block)
  super(tag_filter_from(tag), &block)
end

#cassette_library_dirString

Gets the directory to read cassettes from and write cassettes to.

Returns:

  • (String)

    the directory to read cassettes from and write cassettes to



15
16
17
# File 'lib/vcr/configuration.rb', line 15

def cassette_library_dir
  VCR.cassette_persisters[:file_system].storage_location
end

#cassette_library_dir=(dir) ⇒ void

Note:

This is only necessary if you use the ‘:file_system` cassette persister (the default).

This method returns an undefined value.

Sets the directory to read cassettes from and writes cassettes to.

Examples:

VCR.configure do |c|
  c.cassette_library_dir = 'spec/cassettes'
end

Parameters:

  • dir (String)

    the directory to read cassettes from and write cassettes to



30
31
32
# File 'lib/vcr/configuration.rb', line 30

def cassette_library_dir=(dir)
  VCR.cassette_persisters[:file_system].storage_location = dir
end

#cassette_persistersVCR::Cassette::Persisters

Note:

Custom persisters must implement the following interface:

  • persister` # returns previously persisted content

  • persister = content` # persists given content

Gets the registry of cassette persisters. Use it to register a custom persister.

Examples:

VCR.configure do |c|
  c.cassette_persisters[:my_custom_persister] = my_custom_persister
end

Returns:



269
270
271
# File 'lib/vcr/configuration.rb', line 269

def cassette_persisters
  VCR.cassette_persisters
end

#cassette_serializersVCR::Cassette::Serializers

Note:

Custom serializers must implement the following interface:

  • ‘file_extension # => String`

  • ‘serialize(Hash) # => String`

  • ‘deserialize(String) # => Hash`

Gets the registry of cassette serializers. Use it to register a custom serializer.

Examples:

VCR.configure do |c|
  c.cassette_serializers[:my_custom_serializer] = my_custom_serializer
end

Returns:



253
254
255
# File 'lib/vcr/configuration.rb', line 253

def cassette_serializers
  VCR.cassette_serializers
end

#configure_rspec_metadata!Object

Configures RSpec to use a VCR cassette for any example tagged with ‘:vcr`.



418
419
420
421
422
423
# File 'lib/vcr/configuration.rb', line 418

def configure_rspec_metadata!
  unless @rspec_metadata_configured
    VCR::RSpec::Metadata.configure!
    @rspec_metadata_configured = true
  end
end

#define_cassette_placeholder(placeholder, tag = nil) {|interaction| ... } ⇒ Object Also known as: filter_sensitive_data

Sets up a #before_record and a #before_playback hook that will insert a placeholder string in the cassette in place of another string. You can use this as a generic way to interpolate a variable into the cassette for a unique string. It’s particularly useful for unique sensitive strings like API keys and passwords.

Examples:

VCR.configure do |c|
  # Put "<GITHUB_API_KEY>" in place of the actual API key in
  # our cassettes so we don't have to commit to source control.
  c.filter_sensitive_data('<GITHUB_API_KEY>') { GithubClient.api_key }

  # Put a "<USER_ID>" placeholder variable in our cassettes tagged with
  # :user_cassette since it can be different for different test runs.
  c.define_cassette_placeholder('<USER_ID>', :user_cassette) { User.last.id }
end

Parameters:

  • placeholder (String)

    The placeholder string.

  • tag (Symbol) (defaults to: nil)

    Set this to apply this only to cassettes with a matching tag; otherwise it will apply to every cassette.

Yields:

  • block that determines what string to replace

Yield Parameters:

Yield Returns:

  • the string to replace



225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/vcr/configuration.rb', line 225

def define_cassette_placeholder(placeholder, tag = nil, &block)
  before_record(tag) do |interaction|
    orig_text = call_block(block, interaction)
    log "before_record: replacing #{orig_text.inspect} with #{placeholder.inspect}"
    interaction.filter!(orig_text, placeholder)
  end

  before_playback(tag) do |interaction|
    orig_text = call_block(block, interaction)
    log "before_playback: replacing #{orig_text.inspect} with #{placeholder.inspect}"
    interaction.filter!(placeholder, orig_text)
  end
end

#hook_into(*hooks) ⇒ Object

Configures which libraries VCR will hook into to intercept HTTP requests.

Examples:

VCR.configure do |c|
  c.hook_into :webmock, :typhoeus
end

Parameters:

  • hooks (Array<Symbol>)

    List of libraries. Valid values are ‘:webmock`, `:typhoeus`, `:excon` and `:faraday`.

Raises:



65
66
67
68
# File 'lib/vcr/configuration.rb', line 65

def hook_into(*hooks)
  hooks.each { |a| load_library_hook(a) }
  invoke_hook(:after_library_hooks_loaded)
end

#ignore_hosts(*hosts) ⇒ Object Also known as: ignore_host

Specifies host(s) that VCR should ignore.

Parameters:

  • hosts (Array<String>)

    List of hosts to ignore

See Also:



75
76
77
# File 'lib/vcr/configuration.rb', line 75

def ignore_hosts(*hosts)
  VCR.request_ignorer.ignore_hosts(*hosts)
end

#ignore_localhost=(value) ⇒ Object

Sets whether or not VCR should ignore localhost requests.

Parameters:

  • value (Boolean)

    the value to set

See Also:



94
95
96
# File 'lib/vcr/configuration.rb', line 94

def ignore_localhost=(value)
  VCR.request_ignorer.ignore_localhost = value
end

#ignore_request {|request| ... } ⇒ Object

Defines what requests to ignore using a block.

Examples:

VCR.configure do |c|
  c.ignore_request do |request|
    uri = URI(request.uri)
    # ignore only localhost requests to port 7500
    uri.host == 'localhost' && uri.port == 7500
  end
end

Yields:

  • the callback

Yield Parameters:

Yield Returns:

  • (Boolean)

    whether or not to ignore the request



112
113
114
# File 'lib/vcr/configuration.rb', line 112

def ignore_request(&block)
  VCR.request_ignorer.ignore_request(&block)
end

#preserve_exact_body_bytes {|http_message, cassette| ... } ⇒ void

Note:

This is usually only necessary when the HTTP server returns a response with a non-standard encoding or with a body containing invalid bytes for the given encoding. Note that when you set this, and the block returns true, you sacrifice the human readability of the data in the cassette.

This method returns an undefined value.

Sets a callback that determines whether or not to base64 encode the bytes of a request or response body during serialization in order to preserve them exactly.

Examples:

VCR.configure do |c|
  c.preserve_exact_body_bytes do |http_message|
    http_message.body.encoding.name == 'ASCII-8BIT' ||
    !http_message.body.valid_encoding?
  end
end

Yields:

  • the callback

Yield Parameters:

  • http_message (#body, #headers)

    the ‘VCR::Request` or `VCR::Response` object being serialized

  • cassette (VCR::Cassette)

    the cassette the http message belongs to

Yield Returns:

  • (Boolean)

    whether or not to preserve the exact bytes for the body of the given HTTP message

See Also:



478
# File 'lib/vcr/configuration.rb', line 478

define_hook :preserve_exact_body_bytes

#preserve_exact_body_bytes_for?(http_message) ⇒ Boolean

Returns whether or not the body of the given HTTP message should be base64 encoded during serialization in order to preserve the bytes exactly.

Parameters:

  • http_message (#body, #headers)

    the ‘VCR::Request` or `VCR::Response` object being serialized

Returns:

  • (Boolean)

    whether or not the body of the given HTTP message should be base64 encoded during serialization in order to preserve the bytes exactly.

See Also:



484
485
486
# File 'lib/vcr/configuration.rb', line 484

def preserve_exact_body_bytes_for?(http_message)
  invoke_hook(:preserve_exact_body_bytes, http_message, VCR.current_cassette).any?
end

#register_request_matcher(name) {|request_1, request_2| ... } ⇒ Object

Registers a request matcher for later use.

Examples:

VCR.configure do |c|
  c.register_request_matcher :port do |request_1, request_2|
    URI(request_1.uri).port == URI(request_2.uri).port
  end
end

VCR.use_cassette("my_cassette", :match_requests_on => [:method, :host, :port]) do
  # ...
end

Parameters:

  • name (Symbol)

    the name of the request matcher

Yields:

  • the request matcher

Yield Parameters:

Yield Returns:

  • (Boolean)

    whether or not these two requests should be considered equivalent



198
199
200
# File 'lib/vcr/configuration.rb', line 198

def register_request_matcher(name, &block)
  VCR.request_matchers.register(name, &block)
end

#stub_with(*adapters) ⇒ Object

Deprecated.

Use #hook_into instead.

See Also:



26
27
28
29
# File 'lib/vcr/deprecations.rb', line 26

def stub_with(*adapters)
  warn "WARNING: `VCR.configure { |c| c.stub_with ... }` is deprecated. Use `VCR.configure { |c| c.hook_into ... }` instead."
  hook_into(*adapters)
end

#unignore_hosts(*hosts) ⇒ Object Also known as: unignore_host

Specifies host(s) that VCR should stop ignoring.

Parameters:

  • hosts (Array<String>)

    List of hosts to unignore

See Also:



84
85
86
# File 'lib/vcr/configuration.rb', line 84

def unignore_hosts(*hosts)
  VCR.request_ignorer.unignore_hosts(*hosts)
end