Home / RSpec JSON Expectations

Matching JSON Values with Regular Expressions in RSpec

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.

Some JSON values are never the same twice: generated IDs, timestamps, tokens and URLs with signatures. You still want to check that they are present and well formed. Placing a regular expression where a literal value would go is a clean way to do that in a partial JSON expectation.

Basic pattern matching

it "issues a session token" do
  body = JSON.parse(response.body)

  expect(body).to include_json(
    token: /\A[a-f0-9]{32}\z/,
    expires_at: /\A\d{4}-\d{2}-\d{2}T/,
    user: { email: /@example\.com\z/ }
  )
end

Each regular expression is applied to the value at that path. A string value passes if it matches; a missing key fails.

Anchor your patterns

The most common mistake is an unanchored pattern. /[0-9]+/ matches "abc1" because it only needs one digit somewhere. Use \A and \z to require the whole value to match. Prefer \z over $, since $ matches before a trailing newline.

Good uses

When a regex is the wrong tool

If you can control the value, control it. Freezing time or stubbing a token generator and asserting an exact value is a stronger test than a pattern. Regular expressions are also a poor fit for numbers: /\d+/ will not match the integer 42 unless the matcher converts it to a string first, so check numeric fields with literal values or with a separate expectation such as be_a(Integer).

Keep failures readable

When a pattern fails, the message shows the pattern and the actual value. Short, specific patterns produce messages a teammate can act on; one enormous regex for a whole URL does not. Split complex checks into several smaller expectations if that makes the failure clearer.

More on RSpec JSON Expectations

Explore the archive