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



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

def at_path(path)
  @path = path
  self
end

#descriptionObject



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

def description
  message_with_path("include JSON")
end

#excluding(*keys) ⇒ Object



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

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

#failure_message_for_shouldObject



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

def failure_message_for_should
  message_with_path("Expected included JSON")
end

#failure_message_for_should_notObject



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

def failure_message_for_should_not
  message_with_path("Expected excluded JSON")
end

#from_file(path) ⇒ Object



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

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

#including(*keys) ⇒ Object



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

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
23
# 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)
  when String then actual.include?(expected)
  else false
  end
end