Created
April 10, 2024 15:14
-
-
Save ll14m4n/f66d130f4af524294ea49b4cb5192450 to your computer and use it in GitHub Desktop.
RSpec match nested JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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