Class: JSON::SchemaMatchers::MatchJsonSchemaMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/json-schema-rspec/matchers/json_schema_matcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(schema_name, validation_opts = {}) ⇒ MatchJsonSchemaMatcher

Returns a new instance of MatchJsonSchemaMatcher.



11
12
13
14
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 11

def initialize(schema_name, validation_opts = {})
  @schema_name = schema_name
  @validation_opts = validation_opts
end

Instance Method Details

#===(other) ⇒ Object



44
45
46
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 44

def ===(other)
  matches?(other)
end

#descriptionObject



56
57
58
59
60
61
62
63
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 56

def description
  if @errors.any?
    # ignore the preamble in a diff
    @errors[1..-1].join("\n")
  else
    "match JSON schema identified by #{@schema_name}"
  end
end

#failure_messageObject



48
49
50
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 48

def failure_message
  @errors.join("\n")
end

#failure_message_when_negatedObject



52
53
54
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 52

def failure_message_when_negated
  "Expected JSON object not to match schema identified by #{@schema_name}"
end

#inspectObject Also known as: to_s



34
35
36
37
38
39
40
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 34

def inspect
  if @errors.any?
    failure_message
  else
    super
  end
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 16

def matches?(actual)
  @actual = actual

  schema = schema_for_name(@schema_name)
  if schema.nil?
    @errors = [ "No schema defined for #{@schema_name}.  Available schemas are #{RSpec.configuration.json_schemas.keys}." ]
    return false
  end
  @errors = JSON::Validator.fully_validate(schema_for_name(@schema_name), @actual, @validation_opts)

  if @errors.any?
    @errors.unshift("Expected JSON object to match schema identified by #{@schema_name}, #{@errors.count} errors in validating")
    return false
  else
    return true
  end
end

#schema_for_name(schema) ⇒ Object



65
66
67
# File 'lib/json-schema-rspec/matchers/json_schema_matcher.rb', line 65

def schema_for_name(schema)
  RSpec.configuration.json_schemas[schema]
end