Setting up OpenAPI Contract Tests with a Rails and RSpec codebase
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.
Update 2022-11-21: I've got a full article about how to completely retrofit OpenAPI to a Rails codebase that may be of interest
Thanks to the excellent post 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 🚀