Real API responses are rarely flat. An order has a customer, the customer has an address, and the order has line items. A partial JSON matcher earns its keep by applying the same "only check what I list" rule at every level of nesting.
Nesting follows the shape of the response
order = {
"id" => 901,
"status" => "paid",
"customer" => {
"name" => "Grace",
"address" => { "city" => "Leeds", "postcode" => "LS1 1AA" }
}
}
expect(order).to include_json(
status: "paid",
customer: {
address: { city: "Leeds" }
}
)The expectation passes because every key it lists exists with the expected value. customer.name and address.postcode are ignored.
Symbols and strings
Parsed JSON has string keys, while Ruby code tends to use symbol keys. A well designed matcher treats them as equal so you can write the expectation in idiomatic Ruby. If you write your own helper, normalise both sides, for example with transform_keys(&:to_s) applied recursively.
Arrays inside hashes
Arrays need a decision: does the expectation describe the first elements in order, or any elements in any order? Check how your matcher behaves, and write the spec so the intent is obvious:
expect(order).to include_json(
line_items: [
{ sku: "TEA-01", quantity: 2 }
]
)If order does not matter, it is often clearer to extract the array and use RSpec's own include or contain_exactly with a_hash_including.
Tips for deep structures
- Stop at the depth the spec is about. A spec for order status does not need the postcode.
- Extract repeated shapes into helper methods, such as
expected_address(city: "Leeds"). - When a nested check fails, read the reported path first; it tells you which level broke.
- Avoid asserting on
nilby accident. Listingdiscount: nilrequires the key to exist with a null value, which may be stricter than you meant.