Skip to content

Instantly share code, notes, and snippets.

@marclove
Created May 2, 2012 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marclove/2574131 to your computer and use it in GitHub Desktop.
Save marclove/2574131 to your computer and use it in GitHub Desktop.
RSpec matcher for JSON
# Will accept either a Hash or a JSON string as the expected value. Use it like this:
#
# @response.body.should be_json({:my => {:expected => ["json","hash"]}})
# @response.body.should be_json('{"my":{"expected":["json","hash"]}}')
RSpec::Matchers.define :be_json do |expected|
match do |actual|
actual = ActiveSupport::JSON.decode(actual).with_indifferent_access
expected = ActiveSupport::JSON.decode(expected) unless expected.is_a?(Hash)
expected = expected.with_indifferent_access
actual.diff(expected) == {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment