Skip to content

Instantly share code, notes, and snippets.

@dangalipo
Last active December 30, 2015 18:19
Show Gist options
  • Save dangalipo/7866794 to your computer and use it in GitHub Desktop.
Save dangalipo/7866794 to your computer and use it in GitHub Desktop.
RSpec::Matchers.define :match_unordered_json_string do |json_string|
match do |actual|
sort_hash(JSON.parse(actual)).to_json == sort_hash(JSON.parse(json_string)).to_json
end
description do
"be in the correct order"
end
failure_message_for_should do |actual|
"expected\n'#{actual}'\n to equal:\n'#{json_string}'\n after sorting"
end
failure_message_for_should_not do |actual|
"expected\n'#{actual}'\n not to equal:\n'#{json_string}'\n after sorting"
end
end
def sort_hash(hash)
sorted_hash = {}
hash.keys.sort.each do |k|
if hash[k].is_a?(Hash)
sorted_hash[k] = sort_hash(hash[k])
elsif hash[k].is_a?(Array) && hash[k].first.is_a?(Hash)
sorted_hash[k] = hash[k].collect{ |h| sort_hash(h) }
else
sorted_hash[k] = hash[k]
end
end
sorted_hash
end
###
expect(response_body).to match_unordered_json_string({authentication: json_user.expected_response(user, user, includes: [:authentication_token])}.to_json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment