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
# File 'lib/json_spec/matchers/include_json.rb', line 8

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

Instance Method Details

#at_path(path) ⇒ Object



24
25
26
27
# File 'lib/json_spec/matchers/include_json.rb', line 24

def at_path(path)
  @path = path
  self
end

#descriptionObject



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

def description
  message_with_path("include JSON")
end

#excluding(*keys) ⇒ Object



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

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

#failure_message_for_shouldObject



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

def failure_message_for_should
  message_with_path("Expected included JSON")
end

#failure_message_for_should_notObject



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

def failure_message_for_should_not
  message_with_path("Expected excluded JSON")
end

#from_file(path) ⇒ Object



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

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

#including(*keys) ⇒ Object



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

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

#matches?(actual_json) ⇒ Boolean

Returns:

  • (Boolean)


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

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

  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)
  else false
  end
end