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) ⇒ MatchJsonSchemaMatcher

Returns a new instance of MatchJsonSchemaMatcher.



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

def initialize(schema_name)
  @schema_name = schema_name
end

Instance Method Details

#failure_messageObject



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

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

#failure_message_when_negatedObject



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

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

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


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

def matches?(actual)
  @actual = actual
  schema = schema_for_name(@schema_name)
  if schema.nil?
    @errors = [
      "No schema defined for #{@schema_name}",
      "Add a line to your RSpec.configure block to define the schema:",
      "  RSpec.configure do |config|",
      "    config.json_schemas[:my_remote_schema] = 'path/to/schema'",
      "    config.json_schemas[:my_inline_schema] = '{\"json\": \"schema\"}'",
      "  end"]
    return false
  end
  @errors = JSON::Validator.fully_validate(schema_for_name(@schema_name), @actual)

  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



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

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