Recently I was writing code to an API and I noticed that I always wrote something like:

expect(JSON.load(response.body)["data"]["posts"]).to eq "XXX"
expect(JSON.load(response.body)["data"]["authors"]).to eq "XXX"

If you notice you see that:

  • expect().to eq is part of any test, so we need it;
  • JSON.load(response.body)["data"] is too long to write and it is not a syntax for tests;

I was introducing automated test to the company I needed to make it as easy as possible to read/write to people that know about it but not used to write.

The Code!

I wrote this code:

module MyApp
  module Helpers
    def json_response

    def api_response

RSpec.configure do |config|
  config.include MyApp::Helpers

MyApp usually is the same module in config/application.rb in case of a Rails app.

There are two method, first because sometimes we just need the json response and the other one is a normal response from our api.