Skip to content

Instantly share code, notes, and snippets.

@ll14m4n
Created April 10, 2024 15:14
Show Gist options
  • Save ll14m4n/f66d130f4af524294ea49b4cb5192450 to your computer and use it in GitHub Desktop.
Save ll14m4n/f66d130f4af524294ea49b4cb5192450 to your computer and use it in GitHub Desktop.
RSpec match nested JSON
# May be used to match JSON strings in nested array/hashes
# Example:
# RSpec.describe(
# { a: 1,
# whatever: 'else',
# nested_json: '[{"c":3},{"whatever":"else"}]'
# }
# ) do
# it { is_expected.to match(
# a_hash_including(
# a: 1,
# nested_json: json_match(
# a_collection_including(
# a_hash_including(c: 3)
# )
# )
# )
# )
# }
# end
RSpec::Matchers.define :json_match do |expected|
match do |actual_json|
begin
actual = JSON.parse(actual_json, symbolize_names: true)
rescue JSON::ParserError
return false
end
expect(actual).to match(expected)
end
failure_message do |actual|
"expected #{actual} to match #{expected} as JSON"
end
failure_message_when_negated do |actual|
"expected #{actual} not to match #{expected} as JSON"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment