Class: RSpec::LLM::Matchers::MatchJsonSchema
- Inherits:
-
Object
- Object
- RSpec::LLM::Matchers::MatchJsonSchema
- 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
stringand markedrequired.
Instance Method Summary collapse
- #description ⇒ Object
- #failure_message ⇒ Object
- #failure_message_when_negated ⇒ Object
-
#initialize(schema) ⇒ MatchJsonSchema
constructor
A new instance of MatchJsonSchema.
- #matches?(actual) ⇒ Boolean
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
#description ⇒ Object
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_message ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 42 def 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_negated ⇒ Object
50 51 52 |
# File 'lib/rspec/llm/matchers/match_json_schema.rb', line 50 def "expected response NOT to match JSON schema, but it did.\n\nResponse:\n#{@actual}" end |
#matches?(actual) ⇒ 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 |