Home / RSpec JSON Expectations

Nested Hashes in Partial JSON Matching

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.

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

More on RSpec JSON Expectations

Explore the archive