RSpec Json Expectations - Set of Matchers and Helpers to Allow You Test Your API Responses Like a Pro

api, json, rspec, ruby

rspec-json_expectations library provides powerful include_json matcher for your RSpec suites. It allows to match string with JSON or already parsed ruby Hash against other ruby Hash, which is very convenient and creates very readable spec code. Lets jump to some examples.

It can handle some plain json:

1
2
3
4
5
6
7
it "has basic info about user" do
  expect(response).to include_json(
    id: 25,
    email: "john.smith@example.com",
    name: "John"
  )
end

And nested json:

1
2
3
4
5
6
7
8
9
it "has gamification info for user" do
  expect(response).to include_json(
    code: "7wxMw32",
    gamification: {
      rating: 93,
      score: 355
    }
  )
end

You can even do some regex matching:

1
2
3
4
5
6
it "has basic info about user" do
  expect(response).to include_json(
    code: /^[a-z0-9]{10}$/,
    url: %r{api/v5/users/[a-z0-9]{10}.json}
  )
end

Most can agree, that this method of specifying JSON responses in ruby is very readable, but what about failure messages? How helpful they are?

For example with failure in nested JSON things can become tricky, but this gem solves them quite nice:

1
2
3
4
             json atom at path "gamification/score" is not equal to expected value:

               expected: 355
                    got: 397

If you match with nested Arrays you will get numbers in your JSON path within failure message, for example:

1
2
3
4
5
6
             json atom at path "results/2/badges/0" is not equal to expected value:

               expected: "first flight"
                    got: "day & night"

             json atom at path "results/3" is missing

For further reading and instructions: github and cucumber generated documentation.

Feedback is highly appreciated, contact me on twitter (@tdd_fellow) or on github issues.