Testing your JSON API in Ruby with dry-rb

Paul Götze
7 min readOct 25, 2021
Dryer icon by photo3idea_studio from flaticon.com

When writing a JSON API with Ruby in your favorite web framework, you will certainly come to a point, where you have to decide how to test your endpoints. In this article I’m going to show one of my preferred ways to test the structure of JSON responses in a clear and readable way—by making use of the dry-schema gem and some other dry-rb libraries.

There’s Different Ways

When it comes to testing your JSON API endpoints in Ruby, you can go for plenty of different approaches. The simplest probably is to check the status code and explicitly assert each value of you response data.

Let’s assume we want to test a GET /todos endpoint, which returns to-do items like this:

Then a simple test for this response could look like this:

However, this approach is a bit cumbersome for large response bodies and can result in a lot of accesses to nested hash keys, until you get to the value you actually want to check. It will also take you quite some effort to adjust the tests as soon as some keys or values in the JSON response change.

So, instead of checking for each exact value, you could move up one level of abstraction and only check for the right structure and data types in your response body. Again there’s different ways to do that.

You could use JSON Schema files and validate your response against them, as is described here:

--

--

Paul Götze

Authoring code. Drawing stuff. Comics addict and fan of bad jokes. Creator of adoptoposs.org & zarenwitze.de.