Created
September 14, 2011 14:18
-
-
Save dtuite/1216676 to your computer and use it in GitHub Desktop.
RSpec2 JSON matcher
This file contains hidden or 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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Most of the credit needs to go to Bill Burcham for his code in this thread. I just converted for Rspec2.