Using Webmock with RSpec to Stub HTTP Requests in Tests

Опубликовано: 11 Июнь 2026
на канале: Brett Codes
2,848
37

When writing code that interacts with external APIs, you almost always don't want to make actual HTTP requests in your test suite because it's slow and could you get you rate limited (causing unexpected failures). The general best practice is to mock the API request and response. One option is VCR, which I covered in a previous episode. VCR is a bit intense in that it records the request and response in a YAML file, which can lead to a considerable amount of accuracy but comes with the overhead of maintaining those YAML files. An alternative is to use Webmock, which takes a little more work to set up the requests and responses, but I find it quite nice to work with and manage.

In this episode, I remove VCR from the past episode and replace it with Webmock, as well as cover adding specs for non-successful requests. This is all done with RSpec, but Webmocks supports other test frameworks too.

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

Source code from the episode: https://github.com/brettchalupa/scree...

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

Webmock docs: https://github.com/bblimke/webmock#we...

Dependencies from the episode:
Ruby 2.7.3
RSpec 3.10.0
Sinatra 2.1.0
Webmock 3.13.0