Testing: WebMock & VCR
This course covers how to keep tests from making live HTTP calls, using an outbound service in this app as the example. It explains why network calls make a test suite flaky and slow. It covers WebMock's stub_request, to_return and disable_net_connect!, and VCR's cassettes and record modes. It reads Partners::FetchSiteIconService and the hand-rolled fake_http helper its spec passes through an http: keyword argument. It also looks at how OmniAuth's test mode skips the GitHub token exchange, and ends with a small stub registry challenge in plain Ruby.
What you'll learn
- ✓Why live network calls make tests unreliable
- ✓Stubbing requests with WebMock's stub_request, with and to_return
- ✓Making unstubbed requests fail with disable_net_connect!
- ✓Recording and replaying HTTP with VCR cassettes and record modes
- ✓Faking Net::HTTP through a dependency-injection seam
- ✓How OmniAuth test mode replaces the GitHub token exchange in specs
Why a test that touches the network is a test you can't trust
app/services/partners/fetch_site_icon_service.rb, which ships in this app today, does something none of the earlier testing courses touched. It opens a Net::HTTP connection to a partner's own website, downloads the HTML, looks for an icon link, and downloads that too.
Read the full lesson free →Curriculum
7 lessonsWhy a test that touches the network is a test you can't trust
Why a live network call in a test makes the suite flaky, using this app's site-icon service.
What WebMock does: stub_request, to_return, and disable_net_connect!
WebMock's stub_request, with and to_return syntax, the disable_net_connect! safety net and its RSpec matchers.
What VCR does differently: record once, replay from a cassette
How VCR records a real request once into a cassette file, replays it, and offers four record modes.
Reading this app's site-icon service end to end
A walk through FetchSiteIconService: icon priority, the http: injection seam, redirects, and content-type and size checks.
How this app's spec fakes the network today, with neither gem
How this app's spec fakes Net::HTTP with a hand-rolled fake_http helper, and the missing disable_net_connect! net.
OAuth: network calls this app doesn't make itself, and how its tests skip them
How the GitHub OAuth token exchange runs inside gem middleware and how OmniAuth test mode skips it in specs.
Putting it together: two gems, and this app's own alternatives
A recap of WebMock, VCR and this app's own alternatives, closing with a plain Ruby stub registry challenge.