Module: VCR

Extended by:
VCR
Includes:
Errors, VariableArgsBlockCaller
Included in:
VCR
Defined in:
lib/vcr.rb,
lib/vcr/errors.rb,
lib/vcr/structs.rb,
lib/vcr/version.rb,
lib/vcr/cassette.rb,
lib/vcr/util/hooks.rb,
lib/vcr/util/logger.rb,
lib/vcr/deprecations.rb,
lib/vcr/configuration.rb,
lib/vcr/library_hooks.rb,
lib/vcr/linked_cassette.rb,
lib/vcr/middleware/rack.rb,
lib/vcr/request_handler.rb,
lib/vcr/request_ignorer.rb,
lib/vcr/middleware/excon.rb,
lib/vcr/cassette/migrator.rb,
lib/vcr/middleware/faraday.rb,
lib/vcr/cassette/persisters.rb,
lib/vcr/library_hooks/excon.rb,
lib/vcr/cassette/serializers.rb,
lib/vcr/util/version_checker.rb,
lib/vcr/cassette/erb_renderer.rb,
lib/vcr/library_hooks/faraday.rb,
lib/vcr/library_hooks/webmock.rb,
lib/vcr/test_frameworks/rspec.rb,
lib/vcr/library_hooks/typhoeus.rb,
lib/vcr/request_matcher_registry.rb,
lib/vcr/test_frameworks/cucumber.rb,
lib/vcr/util/internet_connection.rb,
lib/vcr/cassette/serializers/json.rb,
lib/vcr/cassette/serializers/syck.rb,
lib/vcr/cassette/serializers/yaml.rb,
lib/vcr/cassette/serializers/psych.rb,
lib/vcr/library_hooks/typhoeus_0.4.rb,
lib/vcr/cassette/http_interaction_list.rb,
lib/vcr/cassette/persisters/file_system.rb,
lib/vcr/cassette/serializers/compressed.rb,
lib/vcr/middleware/excon/legacy_methods.rb,
lib/vcr/util/variable_args_block_caller.rb

Overview

Note:

This module is extended onto itself; thus, the methods listed here as instance methods are available directly off of VCR.

The main entry point for VCR.

Defined Under Namespace

Modules: Deprecations, Errors, Hooks, InternetConnection, Middleware, Normalizers, Ping, RSpec, VariableArgsBlockCaller Classes: Cassette, Configuration, CucumberTags, HTTPInteraction, LibraryHooks, LinkedCassette, Logger, Request, RequestHandler, RequestIgnorer, RequestMatcherRegistry, Response, ResponseStatus, VersionChecker

Constant Summary collapse

CassetteMutex =

Mutex to synchronize access to cassettes in a threaded environment

Mutex.new
MainThread =

The main thread in which VCR was loaded

Thread.current

Class Method Summary collapse

Instance Method Summary collapse

Methods included from VariableArgsBlockCaller

#call_block

Class Method Details

.const_missing(const) ⇒ Object



10
11
12
13
14
# File 'lib/vcr/deprecations.rb', line 10

def self.const_missing(const)
  return super unless const == :Config
  warn "WARNING: `VCR::Config` is deprecated.  Use VCR.configuration instead."
  configuration
end

Instance Method Details

#cassette_persistersObject



355
356
357
# File 'lib/vcr.rb', line 355

def cassette_persisters
  @cassette_persisters
end

#cassette_serializersObject



350
351
352
# File 'lib/vcr.rb', line 350

def cassette_serializers
  @cassette_serializers
end

#cassettes(context = current_context) ⇒ Enumerable

Returns list of all cassettes currently being used

Returns:

  • (Enumerable)

    list of all cassettes currently being used



332
333
334
335
336
337
# File 'lib/vcr.rb', line 332

def cassettes(context = current_context)
  linked_context = context[:linked_context]
  linked_cassettes = cassettes(linked_context) if linked_context

  LinkedCassette.list(context[:cassettes], Array(linked_cassettes))
end

#configObject

Deprecated.

Use #configure instead.

See Also:



4
5
6
7
# File 'lib/vcr/deprecations.rb', line 4

def config
  warn "WARNING: `VCR.config` is deprecated.  Use VCR.configure instead."
  configure { |c| yield c }
end

#configurationVCR::Configuration

Returns the VCR configuration.

Returns:



230
231
232
# File 'lib/vcr.rb', line 230

def configuration
  @configuration
end

#configure {|config| ... } ⇒ void

This method returns an undefined value.

Used to configure VCR.

Examples:

VCR.configure do |c|
  c.some_config_option = true
end

Yields:

  • the configuration block

Yield Parameters:



225
226
227
# File 'lib/vcr.rb', line 225

def configure
  yield configuration
end

#cucumber_tags {|t| ... } ⇒ void

This method returns an undefined value.

Sets up `Before` and `After` cucumber hooks in order to use VCR with particular cucumber tags.

Examples:

VCR.cucumber_tags do |t|
  t.tags "tag1", "tag2"
  t.tag "@some_other_tag", :record => :new_episodes
end

Yields:

  • the cucumber tags configuration block

Yield Parameters:

See Also:



247
248
249
250
# File 'lib/vcr.rb', line 247

def cucumber_tags(&block)
  main_object = eval('self', block.binding)
  yield VCR::CucumberTags.new(main_object)
end

#current_cassettenil, VCR::Cassette

The currently active cassette.

Returns:

  • (nil, VCR::Cassette)

    The current cassette or nil if there is no current cassette.



48
49
50
# File 'lib/vcr.rb', line 48

def current_cassette
  cassettes.last
end

#eject_cassette(options = {}) ⇒ VCR::Cassette?

Ejects the current cassette. The cassette will no longer be used. In addition, any newly recorded HTTP interactions will be written to disk.

Parameters:

  • options (Hash) (defaults to: {})

    Eject options.

Options Hash (options):

  • :skip_no_unused_interactions_assertion (Boolean)

    If `true` is given, this will skip the “no unused HTTP interactions” assertion enabled by the `:allow_unused_http_interactions => false` cassette option. This is intended for use when your test has had an error, but your test framework has already handled it.

Returns:



153
154
155
156
157
158
159
# File 'lib/vcr.rb', line 153

def eject_cassette(options = {})
  cassette = cassettes.last
  cassette.eject(options) if cassette
  cassette
ensure
  context_cassettes.delete(cassette)
end

#fibers_available?Boolean

Returns:

  • (Boolean)


378
379
380
# File 'lib/vcr.rb', line 378

def fibers_available?
  @fibers_available
end

#http_interactionsObject



315
316
317
318
# File 'lib/vcr.rb', line 315

def http_interactions
  return current_cassette.http_interactions if current_cassette
  VCR::Cassette::HTTPInteractionList::NullList
end

#insert_cassette(name, options = {}) ⇒ VCR::Cassette

Note:

If you use this method you must call `eject_cassette` when you are done. It is generally recommended that you use #use_cassette unless your code-under-test cannot be run as a block.

Inserts the named cassette using the given cassette options. New HTTP interactions, if allowed by the cassette's `:record` option, will be recorded to the cassette. The cassette's existing HTTP interactions will be used to stub requests, unless prevented by the cassete's `:record` option.

Examples:

VCR.insert_cassette('twitter', :record => :new_episodes)

# ...later, after making an HTTP request:

VCR.eject_cassette

Parameters:

  • name (#to_s)

    The name of the cassette. VCR will sanitize this to ensure it is a valid file name.

  • options (Hash) (defaults to: {})

    The cassette options. The given options will be merged with the configured default_cassette_options.

Options Hash (options):

  • :record (:all, :none, :new_episodes, :once)

    The record mode.

  • :erb (Boolean, Hash)

    Whether or not to evaluate the cassette as an ERB template. Defaults to false. A hash can be used to provide the ERB template with local variables.

  • :match_requests_on (Array<Symbol, #call>)

    List of request matchers to use to determine what recorded HTTP interaction to replay. Defaults to [:method, :uri]. The built-in matchers are :method, :uri, :host, :path, :headers and :body. You can also pass the name of a registered custom request matcher or any object that responds to #call.

  • :re_record_interval (Integer)

    When given, the cassette will be re-recorded at the given interval, in seconds.

  • :tag (Symbol)

    Used to apply tagged `before_record` and `before_playback` hooks to the cassette.

  • :tags (Array<Symbol>)

    Used to apply multiple tags to a cassette so that tagged `before_record` and `before_playback` hooks will apply to the cassette.

  • :update_content_length_header (Boolean)

    Whether or not to overwrite the Content-Length header of the responses to match the length of the response body. Defaults to false.

  • :decode_compressed_response (Boolean)

    Whether or not to decode compressed responses before recording the cassette. This makes the cassette more human readable. Defaults to false.

  • :allow_playback_repeats (Boolean)

    Whether or not to allow a single HTTP interaction to be played back multiple times. Defaults to false.

  • :allow_unused_http_interactions (Boolean)

    If set to false, an error will be raised if a cassette is ejected before all previously recorded HTTP interactions have been used. Defaults to true. Note that when an error has already occurred (as indicated by the `$!` variable) unused interactions will be allowed so that we don't silence the original error (which is almost certainly more interesting/important).

  • :exclusive (Boolean)

    Whether or not to use only this cassette and to completely ignore any cassettes in the cassettes stack. Defaults to false.

  • :serialize_with (Symbol)

    Which serializer to use. Valid values are :yaml, :syck, :psych, :json or any registered custom serializer. Defaults to :yaml.

  • :persist_with (Symbol)

    Which cassette persister to use. Defaults to :file_system. You can also register and use a custom persister.

  • :preserve_exact_body_bytes (Boolean)

    Whether or not to base64 encode the bytes of the requests and responses for this cassette when serializing it. See also `VCR::Configuration#preserve_exact_body_bytes`.

Returns:

Raises:

  • (ArgumentError)

    when the given cassette is already being used.

  • (VCR::Errors::TurnedOffError)

    when VCR has been turned off without using the :ignore_cassettes option.

  • (VCR::Errors::MissingERBVariableError)

    when the `:erb` option is used and the ERB template requires variables that you did not provide.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/vcr.rb', line 126

def insert_cassette(name, options = {})
  if turned_on?
    if cassettes.any? { |c| c.name == name }
      raise ArgumentError.new("There is already a cassette with the same name (#{name}).  You cannot nest multiple cassettes with the same name.")
    end

    cassette = Cassette.new(name, options)
    context_cassettes.push(cassette)
    cassette
  elsif !ignore_cassettes?
    message = "VCR is turned off.  You must turn it on before you can insert a cassette.  " +
              "Or you can use the `:ignore_cassettes => true` option to completely ignore cassette insertions."
    raise TurnedOffError.new(message)
  end
end

#library_hooksObject



345
346
347
# File 'lib/vcr.rb', line 345

def library_hooks
  @library_hooks
end


368
369
370
# File 'lib/vcr.rb', line 368

def link_context(from_thread, to_key)
  @context[to_key] = get_context(from_thread)
end

#real_http_connections_allowed?Boolean

Returns:

  • (Boolean)


321
322
323
324
# File 'lib/vcr.rb', line 321

def real_http_connections_allowed?
  return current_cassette.recording? if current_cassette
  !!(configuration.allow_http_connections_when_no_cassette? || !turned_on?)
end

#record_http_interaction(interaction) ⇒ Object



360
361
362
363
364
365
# File 'lib/vcr.rb', line 360

def record_http_interaction(interaction)
  return unless cassette = current_cassette
  return if VCR.request_ignorer.ignore?(interaction.request)

  cassette.record_http_interaction(interaction)
end

#request_ignorerObject



340
341
342
# File 'lib/vcr.rb', line 340

def request_ignorer
  @request_ignorer
end

#request_matchersRequestMatcherRegistry

Returns the request matcher registry

Returns:



327
328
329
# File 'lib/vcr.rb', line 327

def request_matchers
  @request_matchers
end

#turn_off!(options = {}) ⇒ void

This method returns an undefined value.

Turns VCR off, so that it no longer handles every HTTP request.

Parameters:

  • options (Hash) (defaults to: {})

    hash of options

Options Hash (options):

  • :ignore_cassettes (Boolean)

    controls what happens when a cassette is inserted while VCR is turned off. If `true` is passed, the cassette insertion will be ignored; otherwise a VCR::Errors::TurnedOffError will be raised.

Raises:



280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/vcr.rb', line 280

def turn_off!(options = {})
  if VCR.current_cassette
    raise CassetteInUseError, "A VCR cassette is currently in use (#{VCR.current_cassette.name}). " +
                              "You must eject it before you can turn VCR off."
  end

  set_context_value(:ignore_cassettes, options.fetch(:ignore_cassettes, false))
  invalid_options = options.keys - [:ignore_cassettes]
  if invalid_options.any?
    raise ArgumentError.new("You passed some invalid options: #{invalid_options.inspect}")
  end

  set_context_value(:turned_off, true)
end

#turn_on!void

This method returns an undefined value.

Turns on VCR, if it has previously been turned off.



300
301
302
# File 'lib/vcr.rb', line 300

def turn_on!
  set_context_value(:turned_off, false)
end

#turned_off(options = {}) ⇒ void

This method returns an undefined value.

Turns VCR off for the duration of a block.

Parameters:

  • options (Hash) (defaults to: {})

    hash of options

Raises:

See Also:



260
261
262
263
264
265
266
267
268
# File 'lib/vcr.rb', line 260

def turned_off(options = {})
  turn_off!(options)

  begin
    yield
  ensure
    turn_on!
  end
end

#turned_on?Boolean

Note:

Normally VCR is always turned on; it will only be off if you have explicitly turned it off.

Returns whether or not VCR is turned on

Returns:

  • (Boolean)

    whether or not VCR is turned on

See Also:



310
311
312
# File 'lib/vcr.rb', line 310

def turned_on?
  !context_value(:turned_off)
end


373
374
375
# File 'lib/vcr.rb', line 373

def unlink_context(key)
  @context.delete(key)
end

#use_cassette(name, options = {}) {|cassette| ... } ⇒ void

This method returns an undefined value.

Inserts a cassette using the given name and options, runs the given block, and ejects the cassette.

Examples:

VCR.use_cassette('twitter', :record => :new_episodes) do
  # make an HTTP request
end

Parameters:

  • name (#to_s)

    The name of the cassette. VCR will sanitize this to ensure it is a valid file name.

  • options (Hash) (defaults to: {})

    The cassette options. The given options will be merged with the configured default_cassette_options.

Options Hash (options):

  • :record (:all, :none, :new_episodes, :once)

    The record mode.

  • :erb (Boolean, Hash)

    Whether or not to evaluate the cassette as an ERB template. Defaults to false. A hash can be used to provide the ERB template with local variables.

  • :match_requests_on (Array<Symbol, #call>)

    List of request matchers to use to determine what recorded HTTP interaction to replay. Defaults to [:method, :uri]. The built-in matchers are :method, :uri, :host, :path, :headers and :body. You can also pass the name of a registered custom request matcher or any object that responds to #call.

  • :re_record_interval (Integer)

    When given, the cassette will be re-recorded at the given interval, in seconds.

  • :tag (Symbol)

    Used to apply tagged `before_record` and `before_playback` hooks to the cassette.

  • :tags (Array<Symbol>)

    Used to apply multiple tags to a cassette so that tagged `before_record` and `before_playback` hooks will apply to the cassette.

  • :update_content_length_header (Boolean)

    Whether or not to overwrite the Content-Length header of the responses to match the length of the response body. Defaults to false.

  • :decode_compressed_response (Boolean)

    Whether or not to decode compressed responses before recording the cassette. This makes the cassette more human readable. Defaults to false.

  • :allow_playback_repeats (Boolean)

    Whether or not to allow a single HTTP interaction to be played back multiple times. Defaults to false.

  • :allow_unused_http_interactions (Boolean)

    If set to false, an error will be raised if a cassette is ejected before all previously recorded HTTP interactions have been used. Defaults to true. Note that when an error has already occurred (as indicated by the `$!` variable) unused interactions will be allowed so that we don't silence the original error (which is almost certainly more interesting/important).

  • :exclusive (Boolean)

    Whether or not to use only this cassette and to completely ignore any cassettes in the cassettes stack. Defaults to false.

  • :serialize_with (Symbol)

    Which serializer to use. Valid values are :yaml, :syck, :psych, :json or any registered custom serializer. Defaults to :yaml.

  • :persist_with (Symbol)

    Which cassette persister to use. Defaults to :file_system. You can also register and use a custom persister.

  • :preserve_exact_body_bytes (Boolean)

    Whether or not to base64 encode the bytes of the requests and responses for this cassette when serializing it. See also `VCR::Configuration#preserve_exact_body_bytes`.

Yields:

  • Block to run while this cassette is in use.

Yield Parameters:

  • cassette ((optional) VCR::Cassette)

    the cassette that has been inserted.

Raises:

  • (ArgumentError)

    when the given cassette is already being used.

  • (VCR::Errors::TurnedOffError)

    when VCR has been turned off without using the :ignore_cassettes option.

  • (VCR::Errors::MissingERBVariableError)

    when the `:erb` option is used and the ERB template requires variables that you did not provide.

See Also:



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/vcr.rb', line 178

def use_cassette(name, options = {}, &block)
  unless block
    raise ArgumentError, "`VCR.use_cassette` requires a block. " +
                         "If you cannot wrap your code in a block, use " +
                         "`VCR.insert_cassette` / `VCR.eject_cassette` instead."
  end

  cassette = insert_cassette(name, options)

  begin
    call_block(block, cassette)
  ensure
    eject_cassette
  end
end

#use_cassettes(cassettes, &block) ⇒ Object

Inserts multiple cassettes the given names

cassettes = [

{ name: 'github' },
{ name: 'apple', options: { erb: true } }

] VCR.use_cassettes() do

# make multiple HTTP requests

end



204
205
206
207
208
209
210
211
212
213
# File 'lib/vcr.rb', line 204

def use_cassettes(cassettes, &block)
  cassette = cassettes.pop
  use_cassette(cassette[:name], cassette[:options] || {}) do
    if cassettes.empty?
      block.call
    else
      use_cassettes(cassettes, &block)
    end
  end
end

#versionString

Note:

This string also has singleton methods:

  • `major` [Integer] The major version.

  • `minor` [Integer] The minor version.

  • `patch` [Integer] The patch version.

  • `parts` [Array<Integer>] List of the version parts.

Returns the current VCR version.

Returns:

  • (String)

    the current VCR version.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/vcr/version.rb', line 11

def version
  @version ||= begin
    string = '5.0.0'

    def string.parts
      split('.').map { |p| p.to_i }
    end

    def string.major
      parts[0]
    end

    def string.minor
      parts[1]
    end

    def string.patch
      parts[2]
    end

    string
  end
end