Sha256: aa37a49ac3c9d095d75187e53a49a74df89373febcb51ca055d8ff0cbcc93c60

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

module JsonSpec
  module Matchers
    class HaveJsonType
      include JsonSpec::Helpers
      include JsonSpec::Messages

      def initialize(type)
        @classes = type_to_classes(type)
      end

      def matches?(json)
        @ruby = parse_json(json, @path)
        @classes.any?{|c| c === @ruby }
      end

      def at_path(path)
        @path = path
        self
      end

      def failure_message_for_should
        message_with_path("Expected JSON value type to be #{@classes.join(", ")}, got #{@ruby.class}")
      end

      def failure_message_for_should_not
        message_with_path("Expected JSON value type to not be #{@classes.join(", ")}, got #{@ruby.class}")
      end

      def description
        message_with_path(%(have JSON type "#{@classes.join(", ")}"))
      end

      private
        def type_to_classes(type)
          case type
          when Class then [type]
          when Array then type.map{|t| type_to_classes(t) }.flatten
          else
            case type.to_s.downcase
            when "boolean"     then [TrueClass, FalseClass]
            when "object"      then [Hash]
            when "nil", "null" then [NilClass]
            else [Module.const_get(type.to_s.capitalize)]
            end
          end
        end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
json_spec-1.1.1 lib/json_spec/matchers/have_json_type.rb
json_spec-1.1.0 lib/json_spec/matchers/have_json_type.rb
json_spec-1.0.3 lib/json_spec/matchers/have_json_type.rb
json_spec-1.0.2 lib/json_spec/matchers/have_json_type.rb
json_spec-1.0.0 lib/json_spec/matchers/have_json_type.rb