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
endThe 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
- One behaviour per example. Test creation in one example and listing in another.
- List only promised fields. If the client app reads
titleandyear, assert those. - Use literal values you set up. Values you created in the spec make the expectation self explanatory.
- 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.