Class: RSpec::LLM::Matchers::MatchJsonSchema

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/llm/matchers/match_json_schema.rb

Overview

Asserts the actual value parses as JSON and conforms to the provided JSON Schema (a Hash, JSON string, or schema file path).

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ MatchJsonSchema

Returns a new instance of MatchJsonSchema.



12
13
14
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 12

def initialize(schema)
  @schema = schema
end

Instance Method Details

#descriptionObject



25
26
27
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 25

def description
  "match JSON schema"
end

#failure_messageObject



29
30
31
32
33
34
35
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 29

def failure_message
  if @parse_error
    "expected response to parse as JSON, but got: #{@parse_error}\n\nResponse:\n#{@actual}"
  else
    "expected response to match JSON schema, but got errors:\n#{@errors.join("\n")}\n\nResponse:\n#{@actual}"
  end
end

#failure_message_when_negatedObject



37
38
39
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 37

def failure_message_when_negated
  "expected response NOT to match JSON schema, but it did.\n\nResponse:\n#{@actual}"
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 16

def matches?(actual)
  @actual = actual
  @parsed = parse(actual)
  return false if @parse_error

  @errors = JSON::Validator.fully_validate(@schema, @parsed)
  @errors.empty?
end