Back to Browse

Using VCR with RSpec to Record External HTTP Requests

3.6K views
Jul 2, 2021
31:43

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/screencasts/tree/master/vcr API used in the episode: https://ghibliapi.herokuapp.com/ Blog post I found during the episode: https://fabioperrella.github.io/10_tips_to_help_using_the_VCR_gem_in_your_ruby_test_suite.html 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/brettchalupa

Download

1 formats

Video Formats

360pmp447.5 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

Using VCR with RSpec to Record External HTTP Requests | NatokHD