Sha256: 2821d3b3d4da1bcd468a8460f916fcd4a533ac7b8941f6f8c3772609baf86753

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

module GovukSchemas
  module RSpecMatchers
    RSpec::Matchers.define :be_valid_against_schema do |schema_name|
      match do |item|
        schema = Schema.find(publisher_schema: schema_name)
        validator = JSON::Validator.fully_validate(schema, item)
        validator.empty?
      end

      failure_message do |actual|
        ValidationErrorMessage.new(schema_name, "schema", actual).message
      end
    end

    RSpec::Matchers.define :be_valid_against_links_schema do |schema_name|
      match do |item|
        schema = Schema.find(links_schema: schema_name)
        validator = JSON::Validator.fully_validate(schema, item)
        validator.empty?
      end

      failure_message do |actual|
        ValidationErrorMessage.new(schema_name, "links", actual).message
      end
    end
  end

  class ValidationErrorMessage
    attr_reader :schema_name, :type, :payload

    def initialize(schema_name, type, payload)
      @schema_name = schema_name
      @type = type
      @payload = payload
    end

    def message
      <<~doc
      expected the payload to be valid against the '#{schema_name}' schema:

      #{formatted_payload}

      Validation errors:
      #{errors}
      doc
    end

  private

    def errors
      schema = Schema.find(publisher_schema: schema_name)
      validator = JSON::Validator.fully_validate(schema, payload)
      validator.map { |message| "- " + humanized_error(message) }.join("\n")
    end

    def formatted_payload
      return payload if payload.is_a?(String)
      JSON.pretty_generate(payload)
    end

    def humanized_error(message)
      message.gsub("The property '#/'", "The item")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
govuk_schemas-2.3.0 lib/govuk_schemas/rspec_matchers.rb
govuk_schemas-2.2.0 lib/govuk_schemas/rspec_matchers.rb