Setting up OpenAPI Contract Tests with a Rails and RSpec codebase

Featured image for sharing metadata for article

I've recently been working on retrofitting an existing Rails application with an OpenAPI specification, as a way to better understand and interact with the service.

Thanks to the excellent post Liked Validating requests and responses using OpenAPI specification with Committee, I learned about how to get the committee gem to perform the testing validation against a fresh Rails app.

However, the assumption in the post above is that it relies on a non-RSpec driven testing lifecycle, which is fairly common, but the codebase I'm using relies on rspec-rails.

We can continue to follow the post above, but before we generate the scaffolding for the city type, we can start by installing rspec-rails and setting it up:

bundle add rspec-rails && bundle install
bin/rails generate rspec:install

In this rspec-rails codebase, we were using Controller specs which only test the controller through method calls, which are an excellent way to test the controller itself.

Unfortunately, these don't work with Committee, as they're too lightweight. We need to instead use the Request spec, which allows us to execute all (Rack) middleware that is set up for our application, which would include Committee.

If we run the scaffolding command:

bin/rails g scaffold city name:string latitude:float longitude:float demonym:string website:string

We then get a generated request spec which validates that for valid operations, we'll get a valid response.

This still requires us to write the different cases required, but that's it - you're now contract testing 🚀

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby #rails #openapi #testing #contract-testing.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.