File: include_json.rb

package info (click to toggle)
ruby-json-spec 1.1.5-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 312 kB
  • sloc: ruby: 1,059; makefile: 2
file content (63 lines) | stat: -rw-r--r-- 1,632 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module JsonSpec
  module Matchers
    class IncludeJson
      include JsonSpec::Helpers
      include JsonSpec::Exclusion
      include JsonSpec::Messages

      def initialize(expected_json = nil)
        @expected_json = expected_json
        @path = nil
      end

      def matches?(actual_json)
        raise "Expected included JSON not provided" if @expected_json.nil?

        @actual_json = actual_json

        actual = parse_json(actual_json, @path)
        expected = exclude_keys(parse_json(@expected_json))
        case actual
        when Hash then actual.values.map { |v| exclude_keys(v) }.include?(expected)
        when Array then actual.map { |e| exclude_keys(e) }.include?(expected)
        when String then actual.include?(expected)
        else false
        end
      end

      def at_path(path)
        @path = path
        self
      end

      def from_file(path)
        @expected_json = load_json(path)
        self
      end

      def excluding(*keys)
        excluded_keys.merge(keys.map(&:to_s))
        self
      end

      def including(*keys)
        excluded_keys.subtract(keys.map(&:to_s))
        self
      end

      def failure_message
        message_with_path("Expected #{@actual_json} to include #{@expected_json}")
      end
      alias :failure_message_for_should :failure_message

      def failure_message_when_negated
        message_with_path("Expected #{@actual_json} to not include #{@expected_json}")
      end
      alias :failure_message_for_should_not :failure_message_when_negated

      def description
        message_with_path("include JSON")
      end
    end
  end
end