Home / RSpec JSON Expectations

Getting Started with an include_json Matcher

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

An include_json style matcher answers a simple question: does this JSON document contain these keys with these values? This page walks through the first specs you would write with one, using a request spec for a small API.

A first request spec

RSpec.describe "Books API", type: :request do
  it "returns a created book" do
    post "/books", params: { book: { title: "Dune", year: 1965 } }

    expect(response).to have_http_status(:created)
    expect(JSON.parse(response.body)).to include_json(
      title: "Dune",
      year: 1965
    )
  end
end

The status check and the body check are separate on purpose. If the request fails validation, the status expectation fails first with a clear message, instead of a confusing body mismatch.

Reading a failure

Suppose the API returns "year": "1965" as a string. A good matcher reports something like the path year, the expected 1965 and the actual "1965". Types matter: a string and an integer are different JSON values, and that difference often reveals a real bug in serialisation.

Good habits from the start

  1. One behaviour per example. Test creation in one example and listing in another.
  2. List only promised fields. If the client app reads title and year, assert those.
  3. Use literal values you set up. Values you created in the spec make the expectation self explanatory.
  4. Parse once. A small helper such as def json = JSON.parse(response.body) keeps examples short.

Compared with eq

Using eq on a whole parsed body is appropriate for small, stable payloads such as a health check that returns {"status":"ok"}. For anything that grows over time, partial matching keeps specs focused and reduces churn when the API adds fields.

Once flat expectations feel natural, move on to nested hashes and to regular expressions for values that change on every run.

More on RSpec JSON Expectations

Explore the archive