Reading the binary body of a VCR cassette
Reading the binary body of a VCR cassette
Working with VCR is great until you record a response that came with Content-Encoding: gzip and open the YAML to find incomprehensible bytes. The snippet below loads the cassette and prints the body as a string.
1
2
3
4
5
6
7
require 'yaml'
path = 'spec/vcr_cassettes/cassette.yml'
deserialized = YAML.load_file(path)
body_string = deserialized['http_interactions'][0]['response']['body']['string']
puts body_string
If the body is gzipped, add this:
1
2
3
4
5
require 'zlib'
require 'stringio'
decoded = Zlib::GzipReader.new(StringIO.new(body_string)).read
puts decoded
Reference I used: lapointexavier’s gist.
Why this is useful
Unreadable cassettes hide bugs. When a test fails with “expected X, got nothing”, opening the cassette and seeing the actual JSON usually saves 20 minutes of guessing.
This post is licensed under
CC BY 4.0
by the author.