All Lessons / Testing External APIs with VCR

Want more GoRails?

GoRails is packed full with over 350 lessons just like this one.

Sign up to get full access or log in to your account and sit back.

Testing External APIs with VCR

#318 ยท October 29, 2019

Your Teacher | Chris Oliver

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Testing integrations with external APIs in your Rails app can be hard. You don't know what requests are being made (or even the responses), so how can you properly mock them out? VCR to the rescue.

Notes

When your Rails app integrates with external APIs, it can be very hard to test those integrations.

You're probably using a gem that wraps those external APIs, so you don't know what kind of requests are being made. You also don't know the response format you're getting back because the gem parses the response and transforms it into Ruby objects for you.

Not to mention, you don't actually want your test suite hitting a real API because that would be slow. And yet, you do want it to test the real integration, so what's the solution?

VCR lets you record all the HTTP requests in a test into a yaml file that they call a "cassette". It stores all the request and response information and intercepts the requests using Webmock or a similar tool.

The nice part about this is you can run your tests against a real API the first time and record all the external interactions. The second time you run your test suite, it will replay the recorded interactions instead of hitting the external API.

If something goes wrong and a request doesn't match a recorded one in the cassette, VCR will give you an error letting you know. This will help you track down bugs or tests that don't run consistently.

But what if that API changes? What if they release version 2 and change the response? You simply delete the cassette, re-run the test, let it record the new responses and you're good to go.

VCR makes it super duper easy to test HTTP requests in your Rails app without having to worry about maintaining every little piece. You can easily update your cassette fixtures and have your test suite working against the latest version of the API.

Resources

Discussion

Loading...
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.