require 'json-schema'

class SchemaValidator
  include Capybara::DSL

  RSpec::Matchers.define :match_response_schema do |schema|
    match do |response|
      schema_directory = './resources/schemas'
      schema_path = "#{schema_directory}/#{schema}.json"

      # validate!: throws a JSON::Schema::ValidationError with an
      # appropriate message/trace on where the validation failed.
      begin
        return JSON::Validator.validate!(schema_path, response)
      rescue JSON::Schema::ValidationError => e
        error_message("JSON validation error: #{e}\n#{response}")
        raise e
      end
    end
  end
end
