How to use before_record method of VCR Package

Best Vcr_ruby code snippet using VCR.before_record

configuration.rb

Source:configuration.rb Github

copy

Full Screen

...183 # equivalent184 def register_request_matcher(name, &block)185 VCR.request_matchers.register(name, &block)186 end187 # Sets up a {#before_record} and a {#before_playback} hook that will188 # insert a placeholder string in the cassette in place of another string.189 # You can use this as a generic way to interpolate a variable into the190 # cassette for a unique string. It's particularly useful for unique191 # sensitive strings like API keys and passwords.192 #193 # @example194 # VCR.configure do |c|195 # # Put "<GITHUB_API_KEY>" in place of the actual API key in196 # # our cassettes so we don't have to commit to source control.197 # c.filter_sensitive_data('<GITHUB_API_KEY>') { GithubClient.api_key }198 #199 # # Put a "<USER_ID>" placeholder variable in our cassettes tagged with200 # # :user_cassette since it can be different for different test runs.201 # c.define_cassette_placeholder('<USER_ID>', :user_cassette) { User.last.id }202 # end203 #204 # @param placeholder [String] The placeholder string.205 # @param tag [Symbol] Set this to apply this only to cassettes206 # with a matching tag; otherwise it will apply to every cassette.207 # @yield block that determines what string to replace208 # @yieldparam interaction [(optional) VCR::HTTPInteraction::HookAware] the HTTP interaction209 # @yieldreturn the string to replace210 def define_cassette_placeholder(placeholder, tag = nil, &block)211 before_record(tag) do |interaction|212 orig_text = call_block(block, interaction)213 log "before_record: replacing #{orig_text.inspect} with #{placeholder.inspect}"214 interaction.filter!(orig_text, placeholder)215 end216 before_playback(tag) do |interaction|217 orig_text = call_block(block, interaction)218 log "before_playback: replacing #{orig_text.inspect} with #{placeholder.inspect}"219 interaction.filter!(placeholder, orig_text)220 end221 end222 alias filter_sensitive_data define_cassette_placeholder223 # Gets the registry of cassette serializers. Use it to register a custom serializer.224 #225 # @example226 # VCR.configure do |c|227 # c.cassette_serializers[:my_custom_serializer] = my_custom_serializer228 # end229 #230 # @return [VCR::Cassette::Serializers] the cassette serializer registry object.231 # @note Custom serializers must implement the following interface:232 #233 # * `file_extension # => String`234 # * `serialize(Hash) # => String`235 # * `deserialize(String) # => Hash`236 def cassette_serializers237 VCR.cassette_serializers238 end239 # Gets the registry of cassette persisters. Use it to register a custom persister.240 #241 # @example242 # VCR.configure do |c|243 # c.cassette_persisters[:my_custom_persister] = my_custom_persister244 # end245 #246 # @return [VCR::Cassette::Persisters] the cassette persister registry object.247 # @note Custom persisters must implement the following interface:248 #249 # * `persister[storage_key]` # returns previously persisted content250 # * `persister[storage_key] = content` # persists given content251 def cassette_persisters252 VCR.cassette_persisters253 end254 define_hook :before_record255 # Adds a callback that will be called before the recorded HTTP interactions256 # are serialized and written to disk.257 #258 # @example259 # VCR.configure do |c|260 # # Don't record transient 5xx errors261 # c.before_record do |interaction|262 # interaction.ignore! if interaction.response.status.code >= 500263 # end264 #265 # # Modify the response body for cassettes tagged with :twilio266 # c.before_record(:twilio) do |interaction|267 # interaction.response.body.downcase!268 # end269 # end270 #271 # @param tag [(optional) Symbol] Used to apply this hook to only cassettes that match272 # the given tag.273 # @yield the callback274 # @yieldparam interaction [VCR::HTTPInteraction::HookAware] The interaction that will be275 # serialized and written to disk.276 # @yieldparam cassette [(optional) VCR::Cassette] The current cassette.277 # @see #before_playback278 def before_record(tag = nil, &block)279 super(tag_filter_from(tag), &block)280 end281 define_hook :before_playback282 # Adds a callback that will be called before a previously recorded283 # HTTP interaction is loaded for playback.284 #285 # @example286 # VCR.configure do |c|287 # # Don't playback transient 5xx errors288 # c.before_playback do |interaction|289 # interaction.ignore! if interaction.response.status.code >= 500290 # end291 #292 # # Change a response header for playback293 # c.before_playback(:twilio) do |interaction|294 # interaction.response.headers['X-Foo-Bar'] = 'Bazz'295 # end296 # end297 #298 # @param tag [(optional) Symbol] Used to apply this hook to only cassettes that match299 # the given tag.300 # @yield the callback301 # @yieldparam interaction [VCR::HTTPInteraction::HookAware] The interaction that is being302 # loaded.303 # @yieldparam cassette [(optional) VCR::Cassette] The current cassette.304 # @see #before_record305 def before_playback(tag = nil, &block)306 super(tag_filter_from(tag), &block)307 end308 # Adds a callback that will be called with each HTTP request before it is made.309 #310 # @example311 # VCR.configure do |c|312 # c.before_http_request(:real?) do |request|313 # puts "Request: #{request.method} #{request.uri}"314 # end315 # end316 #317 # @param filters [optional splat of #to_proc] one or more filters to apply.318 # The objects provided will be converted to procs using `#to_proc`. If provided,319 # the callback will only be invoked if these procs all return `true`.320 # @yield the callback321 # @yieldparam request [VCR::Request::Typed] the request that is being made322 # @see #after_http_request323 # @see #around_http_request324 define_hook :before_http_request325 define_hook :after_http_request, :prepend326 # Adds a callback that will be called with each HTTP request after it is complete.327 #328 # @example329 # VCR.configure do |c|330 # c.after_http_request(:ignored?) do |request, response|331 # puts "Request: #{request.method} #{request.uri}"332 # puts "Response: #{response.status.code}"333 # end334 # end335 #336 # @param filters [optional splat of #to_proc] one or more filters to apply.337 # The objects provided will be converted to procs using `#to_proc`. If provided,338 # the callback will only be invoked if these procs all return `true`.339 # @yield the callback340 # @yieldparam request [VCR::Request::Typed] the request that is being made341 # @yieldparam response [VCR::Response] the response from the request342 # @see #before_http_request343 # @see #around_http_request344 def after_http_request(*filters)345 super(*filters.map { |f| request_filter_from(f) })346 end347 # Adds a callback that will be executed around each HTTP request.348 #349 # @example350 # VCR.configure do |c|351 # c.around_http_request(lambda {|r| r.uri =~ /api.geocoder.com/}) do |request|352 # # extract an address like "1700 E Pine St, Seattle, WA"353 # # from a query like "address=1700+E+Pine+St%2C+Seattle%2C+WA"354 # address = CGI.unescape(URI(request.uri).query.split('=').last)355 # VCR.use_cassette("geocoding/#{address}", &request)356 # end357 # end358 #359 # @yield the callback360 # @yieldparam request [VCR::Request::FiberAware] the request that is being made361 # @raise [VCR::Errors::NotSupportedError] if the fiber library cannot be loaded.362 # @param filters [optional splat of #to_proc] one or more filters to apply.363 # The objects provided will be converted to procs using `#to_proc`. If provided,364 # the callback will only be invoked if these procs all return `true`.365 # @note This method can only be used on ruby interpreters that support366 # fibers (i.e. 1.9+). On 1.8 you can use separate `before_http_request` and367 # `after_http_request` hooks.368 # @note You _must_ call `request.proceed` or pass the request as a proc on to a369 # method that yields to a block (i.e. `some_method(&request)`).370 # @see #before_http_request371 # @see #after_http_request372 def around_http_request(*filters, &block)373 unless VCR.fibers_available?374 raise Errors::NotSupportedError.new \375 "VCR::Configuration#around_http_request requires fibers, " +376 "which are not available on your ruby intepreter."377 end378 fibers = {}379 fiber_errors = {}380 hook_allowed, hook_declaration = false, caller.first381 before_http_request(*filters) do |request|382 hook_allowed = true383 start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, block)384 end385 after_http_request(lambda { hook_allowed }) do |request, response|386 fiber = fibers.delete(Thread.current)387 resume_fiber(fiber, fiber_errors, response, hook_declaration)388 end389 end390 # Configures RSpec to use a VCR cassette for any example391 # tagged with `:vcr`.392 def configure_rspec_metadata!393 unless @rspec_metadata_configured394 VCR::RSpec::Metadata.configure!395 @rspec_metadata_configured = true396 end397 end398 # An object to log debug output to.399 #400 # @overload debug_logger401 # @return [#puts] the logger402 # @overload debug_logger=(logger)403 # @param logger [#puts] the logger404 # @return [void]405 # @example406 # VCR.configure do |c|407 # c.debug_logger = $stderr408 # end409 # @example410 # VCR.configure do |c|411 # c.debug_logger = File.open('vcr.log', 'w')412 # end413 attr_reader :debug_logger414 # @private (documented above)415 def debug_logger=(value)416 @debug_logger = value417 if value418 @logger = Logger.new(value)419 else420 @logger = Logger::Null421 end422 end423 # @private424 # Logger object that provides logging APIs and helper methods.425 attr_reader :logger426 # Sets a callback that determines whether or not to base64 encode427 # the bytes of a request or response body during serialization in428 # order to preserve them exactly.429 #430 # @example431 # VCR.configure do |c|432 # c.preserve_exact_body_bytes do |http_message|433 # http_message.body.encoding.name == 'ASCII-8BIT' ||434 # !http_message.body.valid_encoding?435 # end436 # end437 #438 # @yield the callback439 # @yieldparam http_message [#body, #headers] the `VCR::Request` or `VCR::Response` object being serialized440 # @yieldparam cassette [VCR::Cassette] the cassette the http message belongs to441 # @yieldreturn [Boolean] whether or not to preserve the exact bytes for the body of the given HTTP message442 # @return [void]443 # @see #preserve_exact_body_bytes_for?444 # @note This is usually only necessary when the HTTP server returns a response445 # with a non-standard encoding or with a body containing invalid bytes for the given446 # encoding. Note that when you set this, and the block returns true, you sacrifice447 # the human readability of the data in the cassette.448 define_hook :preserve_exact_body_bytes449 # @return [Boolean] whether or not the body of the given HTTP message should450 # be base64 encoded during serialization in order to preserve the bytes exactly.451 # @param http_message [#body, #headers] the `VCR::Request` or `VCR::Response` object being serialized452 # @see #preserve_exact_body_bytes453 def preserve_exact_body_bytes_for?(http_message)454 invoke_hook(:preserve_exact_body_bytes, http_message, VCR.current_cassette).any?455 end456 private457 def initialize458 @allow_http_connections_when_no_cassette = nil459 @rspec_metadata_configured = false460 @default_cassette_options = {461 :record => :once,462 :record_on_error => true,463 :match_requests_on => RequestMatcherRegistry::DEFAULT_MATCHERS,464 :allow_unused_http_interactions => true,465 :serialize_with => :yaml,466 :persist_with => :file_system,467 :persister_options => {}468 }469 self.uri_parser = URI470 self.query_parser = CGI.method(:parse)471 self.debug_logger = nil472 register_built_in_hooks473 end474 def load_library_hook(hook)475 file = "vcr/library_hooks/#{hook}"476 require file477 rescue LoadError => e478 raise e unless e.message.include?(file) # in case WebMock itself is not available479 raise ArgumentError.new("#{hook.inspect} is not a supported VCR HTTP library hook.")480 end481 def resume_fiber(fiber, fiber_errors, response, hook_declaration)482 raise fiber_errors[Thread.current] if fiber_errors[Thread.current]483 fiber.resume(response)484 rescue FiberError => ex485 raise Errors::AroundHTTPRequestHookError.new \486 "Your around_http_request hook declared at #{hook_declaration}" \487 " must call #proceed on the yielded request but did not. " \488 "(actual error: #{ex.class}: #{ex.message})"489 end490 def create_fiber_for(fiber_errors, hook_declaration, proc)491 current_thread = Thread.current492 Fiber.new do |*args, &block|493 begin494 # JRuby Fiber runs in a separate thread, so we need to make this Fiber495 # use the context of the calling thread496 VCR.link_context(current_thread, Fiber.current) if RUBY_PLATFORM == 'java'497 proc.call(*args, &block)498 rescue StandardError => ex499 # Fiber errors get swallowed, so we re-raise the error in the parent500 # thread (see resume_fiber)501 fiber_errors[current_thread] = ex502 raise503 ensure504 VCR.unlink_context(Fiber.current) if RUBY_PLATFORM == 'java'505 end506 end507 end508 def start_new_fiber_for(request, fibers, fiber_errors, hook_declaration, proc)509 fiber = create_fiber_for(fiber_errors, hook_declaration, proc)510 fibers[Thread.current] = fiber511 fiber.resume(Request::FiberAware.new(request))512 end513 def tag_filter_from(tag)514 return lambda { true } unless tag515 lambda { |_, cassette| cassette.tags.include?(tag) }516 end517 def request_filter_from(object)518 return object unless object.is_a?(Symbol)519 lambda { |arg| arg.send(object) }520 end521 def register_built_in_hooks522 before_playback(:recompress_response) do |interaction|523 interaction.response.recompress if interaction.response.vcr_decompressed?524 end525 before_playback(:update_content_length_header) do |interaction|526 interaction.response.update_content_length_header527 end528 before_record(:decode_compressed_response) do |interaction|529 interaction.response.decompress if interaction.response.compressed?530 end531 preserve_exact_body_bytes do |http_message, cassette|532 cassette && cassette.tags.include?(:preserve_exact_body_bytes)533 end534 end535 def log_prefix536 "[VCR::Configuration] "537 end538 # @private539 define_hook :after_library_hooks_loaded540 end541end...

Full Screen

Full Screen

configuration_spec.rb

Source:configuration_spec.rb Github

copy

Full Screen

...102 end103 end104 describe "request/configuration interactions", :with_monkey_patches => :fakeweb do105 specify 'the request on the yielded interaction is not typed even though the request given to before_http_request is' do106 before_record_req = before_request_req = nil107 VCR.configure do |c|108 c.before_http_request { |r| before_request_req = r }109 c.before_record { |i| before_record_req = i.request }110 end111 VCR.use_cassette("example") do112 ::Net::HTTP.get_response(URI("http://localhost:#{VCR::SinatraApp.port}/foo"))113 end114 expect(before_record_req).not_to respond_to(:type)115 expect(before_request_req).to respond_to(:type)116 end unless (RUBY_VERSION =~ /^1\.8/ || RUBY_INTERPRETER == :jruby)117 specify 'the filter_sensitive_data option works even when it modifies the URL in a way that makes it an invalid URI' do118 VCR.configure do |c|119 c.filter_sensitive_data('<HOST>') { 'localhost' }120 end121 2.times do122 VCR.use_cassette("example") do123 ::Net::HTTP.get_response(URI("http://localhost:#{VCR::SinatraApp.port}/foo"))124 end125 end126 end127 end128 [:before_record, :before_playback].each do |hook_type|129 describe "##{hook_type}" do130 it 'sets up a tag filter' do131 called = false132 VCR.configuration.send(hook_type, :my_tag) { called = true }133 VCR.configuration.invoke_hook(hook_type, double, double(:tags => []))134 expect(called).to be false135 VCR.configuration.invoke_hook(hook_type, double, double(:tags => [:my_tag]))136 expect(called).to be true137 end138 end139 end140 %w[ filter_sensitive_data define_cassette_placeholder ].each do |method|141 describe "##{method}" do142 let(:interaction) { double('interaction').as_null_object }143 before(:each) { allow(interaction).to receive(:filter!) }144 it 'adds a before_record hook that replaces the string returned by the block with the given string' do145 subject.send(method, 'foo', &lambda { 'bar' })146 expect(interaction).to receive(:filter!).with('bar', 'foo')147 subject.invoke_hook(:before_record, interaction, double.as_null_object)148 end149 it 'adds a before_playback hook that replaces the given string with the string returned by the block' do150 subject.send(method, 'foo', &lambda { 'bar' })151 expect(interaction).to receive(:filter!).with('foo', 'bar')152 subject.invoke_hook(:before_playback, interaction, double.as_null_object)153 end154 it 'tags the before_record hook when given a tag' do155 expect(subject).to receive(:before_record).with(:my_tag)156 subject.send(method, 'foo', :my_tag) { 'bar' }157 end158 it 'tags the before_playback hook when given a tag' do159 expect(subject).to receive(:before_playback).with(:my_tag)160 subject.send(method, 'foo', :my_tag) { 'bar' }161 end162 it 'yields the interaction to the block for the before_record hook' do163 yielded_interaction = nil164 subject.send(method, 'foo', &lambda { |i| yielded_interaction = i; 'bar' })165 subject.invoke_hook(:before_record, interaction, double.as_null_object)166 expect(yielded_interaction).to equal(interaction)167 end168 it 'yields the interaction to the block for the before_playback hook' do169 yielded_interaction = nil170 subject.send(method, 'foo', &lambda { |i| yielded_interaction = i; 'bar' })171 subject.invoke_hook(:before_playback, interaction, double.as_null_object)172 expect(yielded_interaction).to equal(interaction)173 end174 end175 end176 describe "#after_http_request" do177 let(:raw_request) { VCR::Request.new }178 let(:response) { VCR::Response.new }179 def request(type)...

Full Screen

Full Screen

vcr.rb

Source:vcr.rb Github

copy

Full Screen

...3WebMock.allow_net_connect!4VCR.configure do |config|5 config.cassette_library_dir = 'spec/vcr'6 config.hook_into :webmock7 config.before_record { |i| i.response.body.force_encoding 'UTF-8' }8 config.default_cassette_options = {9 record: :new_episodes,10 match_requests_on: %i[method uri]11 }12 config.before_record do |i|13 i.request.headers.clear14 save_headers = %w[Total Per-Page Link Content-Type Content-Length]15 i.response.headers.select! { |key| save_headers.include? key }16 end17end18WebMock.disable_net_connect!(allow_localhost: true)...

Full Screen

Full Screen

before_record

Using AI Code Generation

copy

Full Screen

1 i.response.body.force_encoding('UTF-8')2 i.response.body.force_encoding('UTF-8')3 i.response.body.force_encoding('UTF-8')4 i.response.body.force_encoding('UTF-8')5 i.response.body.force_encoding('UTF-8')6 i.response.body.force_encoding('UTF-8')7 i.response.body.force_encoding('UTF-8')8 i.response.body.force_encoding('UTF-8')9 i.response.body.force_encoding('UTF-8')

Full Screen

Full Screen

before_record

Using AI Code Generation

copy

Full Screen

1 i.response.body.force_encoding('UTF-8')2 i.response.body.force_encoding('UTF-8')3 i.response.body.force_encoding('UTF-8')4 i.response.body.force_encoding('UTF-8')5 i.response.body.force_encoding('UTF-8')

Full Screen

Full Screen

before_record

Using AI Code Generation

copy

Full Screen

1 i.response.body.force_encoding('UTF-8')2 i.request.headers.delete('Authorization')3 i.response.headers.delete('Set-Cookie')4 i.response.body.force_encoding('UTF-8')5 i.request.headers.delete('Authorization')6 i.response.headers.delete('Set-Cookie')7 i.response.body.force_encoding('UTF-8')8 i.request.headers.delete('Authorization')9 i.response.headers.delete('Set-Cookie')10 i.response.body.force_encoding('UTF-8')11 i.request.headers.delete('Authorization')12 i.response.headers.delete('Set-Cookie')13 i.response.body.force_encoding('UTF-8')

Full Screen

Full Screen

before_record

Using AI Code Generation

copy

Full Screen

1 def before_record(http_interaction)2 http_interaction.request.headers.delete('Authorization')3 c.default_cassette_options = { :record => :new_episodes }4 VCR.use_cassette('test') do

Full Screen

Full Screen

before_record

Using AI Code Generation

copy

Full Screen

1 i.request.headers.delete('Authorization')2 i.request.headers.delete('X-Auth-Token')3 VCR.use_cassette('test') do4 i.request.headers.delete('Authorization')

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Vcr_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful