All Lessons / Testing API Integrations with WebMock

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 API Integrations with WebMock

#317 ยท October 23, 2019

Your Teacher

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

About This Episode


When your app integrates with external APIs, it can make testing your code quite tricky. Each API request needs unique IDs, returns results based upon the time, IDs, and other factors and can easily make your test suite break.

WebMock is a fantastic way to stub out and mock your HTTP requests. It will actually throw an exception in your test suite when an HTTP request is made so that you know when you're hitting an external API that you haven't stubbed out correctly.

To create a stub for an HTTP request with WebMock, you simply define the URL, method, params and headers that must match and then define the response's status code, body, and headers it should return. Simple as that.

This allows us to mock external API requests that function just like real ones. We don't have to change our code to get the test suite to run and we can be confident that everything is working.



logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2022 GoRails, LLC. All rights reserved.