[rspec-users] JSON matcher

Michael Schuerig michael at schuerig.de
Mon Apr 6 21:56:57 EDT 2009


Curiously, there doesn't seem to be a matcher around that matches a JSON 
string against an expected ruby object. Below is what I've come up 
with, including some Rails idiosyncrasies. Any suggestions for 
improvements?

Michael

module Spec
  module JSONMatchers
    class BeJsonEql
      def initialize(expected)
        @raw_expected = expected
        @expected = decode(expected, 'expected')
      end

      def matches?(target)
        @raw_target = target
        @target = decode(target, 'target')
        @target == @expected
      end

      def failure_message
        "expected\n#{@raw_target}\n" +
        "to be JSON code equivalent to\n#{@raw_expected}\n" +
        "Difference:\n#{@expected.diff(@target).inspect}"
      end

      def negative_failure_message
        "expected\n#{@raw_target}\n" +
        "to be JSON code different from\n#{@raw_expected}"
      end

      private

      def decode(s, which)
        ActiveSupport::JSON.decode(s)
      rescue ActiveSupport::JSON::ParseError
        raise ArgumentError, "Invalid #{which} JSON string: 
#{s.inspect}"
      end
    end

    def be_json_eql(expected)
      BeJsonEql.new(expected)
    end
  end
end

-- 
Michael Schuerig
mailto:michael at schuerig.de
http://www.schuerig.de/michael/


More information about the rspec-users mailing list