Home / RSpec JSON Expectations

Partial JSON Expectations in RSpec: An Overview

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.

When you test a JSON API, comparing the full response body to a fixture feels thorough, but it is brittle. Add one field to the response and every spec fails. Partial JSON expectations take the opposite approach: you state only the parts of the document the spec cares about, and anything extra is allowed.

The idea in one example

RSpec.describe "GET /users/42" do
  it "returns the user's public profile" do
    body = {
      "id" => 42,
      "name" => "Ada",
      "created_at" => "2014-03-01T10:00:00Z",
      "settings" => { "theme" => "dark", "beta" => false }
    }

    expect(body).to include_json(
      id: 42,
      name: "Ada",
      settings: { theme: "dark" }
    )
  end
end

The spec passes even though created_at and settings.beta were never mentioned. It fails if name changes or if settings.theme disappears.

Why this style works well

When to be stricter

Partial matching can hide accidental leaks. If an endpoint must never return a field such as password_digest, add an explicit negative check:

expect(body).not_to have_key("password_digest")

Similarly, if a list must have an exact length, assert on the length separately, because a partial matcher may only check the elements you list.

Setting it up

Matchers of this kind are usually loaded once in spec_helper.rb or rails_helper.rb, after which they are available in every example group. Parse the response body to a hash before matching, for example with JSON.parse(response.body), so string and symbol keys can be compared consistently.

The related pages cover matching with nested hashes and using regular expressions for values that vary.

More on RSpec JSON Expectations

Explore the archive