Class: JsonSpec::Matchers::IncludeJson

Inherits:
Object
  • Object
show all
Includes:
Exclusion, Helpers, JsonSpec::Messages
Defined in:
lib/json_spec/matchers/include_json.rb

Instance Method Summary collapse

Methods included from JsonSpec::Messages

#message_with_path

Methods included from Exclusion

#exclude_key?, #exclude_keys, #excluded_keys

Methods included from Helpers

#generate_normalized_json, #load_json, #normalize_json, #parse_json

Constructor Details

#initialize(expected_json = nil) ⇒ IncludeJson

Returns a new instance of IncludeJson.



8
9
10
11
# File 'lib/json_spec/matchers/include_json.rb', line 8

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

Instance Method Details

#at_path(path) ⇒ Object



28
29
30
31
# File 'lib/json_spec/matchers/include_json.rb', line 28

def at_path(path)
  @path = path
  self
end

#descriptionObject



58
59
60
# File 'lib/json_spec/matchers/include_json.rb', line 58

def description
  message_with_path("include JSON")
end

#excluding(*keys) ⇒ Object



38
39
40
41
# File 'lib/json_spec/matchers/include_json.rb', line 38

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

#failure_messageObject Also known as: failure_message_for_should



48
49
50
# File 'lib/json_spec/matchers/include_json.rb', line 48

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

#failure_message_when_negatedObject Also known as: failure_message_for_should_not



53
54
55
# File 'lib/json_spec/matchers/include_json.rb', line 53

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

#from_file(path) ⇒ Object



33
34
35
36
# File 'lib/json_spec/matchers/include_json.rb', line 33

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

#including(*keys) ⇒ Object



43
44
45
46
# File 'lib/json_spec/matchers/include_json.rb', line 43

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

#matches?(actual_json) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/json_spec/matchers/include_json.rb', line 13

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