Skip to content

Instantly share code, notes, and snippets.

@dtuite
Created September 14, 2011 14:18
Show Gist options
  • Save dtuite/1216676 to your computer and use it in GitHub Desktop.
Save dtuite/1216676 to your computer and use it in GitHub Desktop.
RSpec2 JSON matcher
# RSpec2 JSON Matcher for functional/controller tests
# Webrat usage example:
#
# it "should be the JSON representation" do
# get :show, id: object.id, format: :json
# response.body.should be_json_eql object.to_json
# end
require 'rspec/expectations'
RSpec::Matchers.define :be_json_eql do | expected |
match do | actual |
@expected = decode(expected, 'expected')
@actual = decode(actual, 'actual')
@actual == @expected
end
failure_message_for_should do | actual |
"expected\n#{actual}\n" +
"to be JSON code equivalent to\n#{expected}\n" +
"Difference:\n#{@expected.diff(@actual).inspect}"
end
failure_message_for_should_not do | actual |
"expected\n#{actual}\n" +
"to be JSON code different from\n#{expected}"
end
def decode(s, which)
ActiveSupport::JSON.decode(s)
rescue ActiveSupport::JSON.parse_error
raise ArgumentError, "Invalid #{which} JSON string: #{s}"
end
end
@dtuite
Copy link
Author

dtuite commented Sep 14, 2011

Most of the credit needs to go to Bill Burcham for his code in this thread. I just converted for Rspec2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment