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
endThe 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
- Intent is visible. A reader sees exactly which fields the endpoint promises.
- Additive changes are safe. New fields do not break old specs, which matches how most APIs evolve.
- Better failure messages. A good matcher reports the path that differed, such as
settings/theme, rather than dumping two large hashes.
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.