Using VCR with RSpec to Record External HTTP Requests

Опубликовано: 23 Июль 2026
на канале: Brett Codes
3,657
49

When your Ruby code makes network requests to external APIs, it can lead to tricky scenarios in your test suite. You likely don't want to make actual HTTP requests because they may fail due to a variety of reasons like CI not supporting external network requests or due to rate limiting. Network requests are generally slow compared to loading data from files. Plus, you want your tests to be deterministic and reliable. If the response from the API returns an error due to rate limiting, you wouldn't want your entire test suite to fail.

Enter VCR. A tool for recording your network requests and saving them as YAML files. It has a simple interface and the ability to work automatically with some Ruby test frameworks.

In this episode I go over building out a simple app in Ruby using Sinatra to fetch the Studio Ghibli films from https://ghibliapi.herokuapp.com/, return a subset of the data, and sort it. I configure VCR to record that request. From there, I show how one could unit test the HTTP request so that there are both end-to-end and unit tests for this simple scenario.

I'll follow this episode up with one on using just Webmock since it's my preferred way of working!

View the source from this episode: https://github.com/brettchalupa/scree...

API used in the episode: https://ghibliapi.herokuapp.com/

Blog post I found during the episode: https://fabioperrella.github.io/10_ti...

VCR docs: https://github.com/vcr/vcr#vcr

Versions used in this screencast:
Ruby 2.7.3
RSpec 3.10.0
Sinatra 2.1.0
VCR 6.0.0
Webmock 3.13.0

Chapters:
00:00 - Intro
01:41 - Setting up the simple app
12:00 - Adding & using VCR
20:48 - Unit testing network requests
27:46 - Closing thoughts

Support my screencasts by buying me a coffee: https://www.buymeacoffee.com/brettcha...