Created
November 24, 2021 19:09
-
-
Save grevych/779f0171f0c159e8febcb7dea270f628 to your computer and use it in GitHub Desktop.
Hacky VCR Cassettes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'vcr' | |
module HackyVCRHelpers | |
def extract_headers_from(request) | |
{ | |
'content_length' => request.headers.env['CONTENT_LENGTH'], | |
'content_type' => request.headers.env['CONTENT_TYPE'], | |
'http_accept' =>request.headers.env['HTTP_ACCEPT'], | |
'http_host' => request.headers.env['HTTP_HOST'], | |
'path_info' => request.headers.env['PATH_INFO'], | |
'query_string' => request.headers.env['QUERY_STRING'], | |
'request_method' => request.headers.env['REQUEST_METHOD'], | |
'request_uri' => request.headers.env['REQUEST_URI'], | |
'server_name' => request.headers.env['SERVER_NAME'], | |
'server_port' => request.headers.env['SERVER_PORT'], | |
} | |
end | |
def vcr_cassette_name_for(metadata) | |
description = | |
if metadata[:description].empty? | |
metadata[:scoped_id] | |
else | |
metadata[:description] | |
end | |
example_group = | |
if metadata.key?(:example_group) | |
metadata[:example_group] | |
else | |
metadata[:parent_example_group] | |
end | |
if example_group | |
[vcr_cassette_name_for(example_group), description].join('/') | |
else | |
description | |
end | |
end | |
end | |
RSpec.configure do |config| | |
config.include HackyVCRHelpers | |
when_tagged_with_hacky_vcr = { :hacky_vcr => lambda { |v| !!v } } | |
VCR.configure do |c| | |
FileUtils.rm_rf(Dir[c.cassette_library_dir + "/hacky"]) | |
config.after(:each, when_tagged_with_hacky_vcr) do |ex| | |
unless response.nil? | |
example = ex.respond_to?(:metadata) ? ex : ex.example | |
cassette_name = "hacky/" + vcr_cassette_name_for(example.metadata) | |
cassette = VCR::Cassette.new(cassette_name) | |
req = VCR::Request.new \ | |
@request.method, | |
@request.url.to_s, | |
@request.body.to_json, | |
extract_headers_from(@request) | |
res = VCR::Response.new \ | |
VCR::ResponseStatus.new(@response.status), | |
@response.headers, | |
@response.body.to_json, | |
nil | |
http_interaction = VCR::HTTPInteraction.new(req, res) | |
cassette.record_http_interaction(http_interaction) | |
cassette.eject | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment