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/ }
)
endEach 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
- UUIDs and hex tokens, where format matters but value does not.
- ISO 8601 timestamps, checking the shape without freezing time.
- URLs, checking the host and path while ignoring query signatures.
- Human readable messages, matching a key phrase rather than the full sentence.
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.