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 schema. The schema argument may be:

  • A Hash — raw JSON Schema (original behaviour, fully backward-compatible).

  • A Class — any Ruby class whose attributes can be introspected:

    * +Data.define+ / +Struct+: attributes are read via +.members+.
    * PORO / ActiveModel: attributes are discovered from public writer
      methods (+#name=+).
    

    In both cases a JSON Schema is derived automatically; every attribute is typed as string and marked required.

Instance Method Summary collapse

Constructor Details

#initialize(schema) ⇒ MatchJsonSchema

Returns a new instance of MatchJsonSchema.



20
21
22
23
24
25
26
27
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 20

def initialize(schema)
  if schema.is_a?(Class)
    @class_name = schema.name || schema.inspect
    @schema     = schema_from_class(schema)
  else
    @schema = schema
  end
end

Instance Method Details

#descriptionObject



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

def description
  @class_name ? "match JSON schema for #{@class_name}" : "match JSON schema"
end

#failure_messageObject



42
43
44
45
46
47
48
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 42

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



50
51
52
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 50

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)


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

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

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