Sha256: 67ebeca4158bbfaf4fc087c2cd7273316c9a5f8615da45adb56926d3559bff39

Contents?: true

Size: 1.56 KB

Versions: 5

Compression:

Stored size: 1.56 KB

Contents

require "json_matchers"

module JsonMatchers
  class RSpec < SimpleDelegator
    attr_reader :schema_name

    def initialize(schema_name, **options)
      @schema_name = schema_name

      super(JsonMatchers::Matcher.new(schema_path, options))
    end

    def failure_message(response)
      <<-FAIL.strip_heredoc
      expected

      #{response.body}

      to match schema "#{schema_name}":

      #{schema_body}

      ---

      #{validation_failure_message}

      FAIL
    end

    def failure_message_when_negated(response)
      <<-FAIL.strip_heredoc
      expected

      #{response.body}

      not to match schema "#{schema_name}":

      #{schema_body}

      ---

      #{validation_failure_message}

      FAIL
    end

    def schema_path
      JsonMatchers.path_to_schema(schema_name)
    end

    def schema_body
      File.read(schema_path)
    end
  end
end

if RSpec.respond_to?(:configure)
  RSpec::Matchers.define :match_response_schema do |schema_name, **options|
    matcher = JsonMatchers::RSpec.new(schema_name, options)

    match do |response|
      matcher.matches?(response)
    end

    if respond_to?(:failure_message)
      failure_message do |response|
        matcher.failure_message(response)
      end

      failure_message_when_negated do |response|
        matcher.failure_message_when_negated(response)
      end
    else
      failure_message_for_should do |response|
        matcher.failure_message(response)
      end

      failure_message_for_should_not do |response|
        matcher.failure_message_when_negated(response)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
json_matchers-0.6.0 lib/json_matchers/rspec.rb
json_matchers-0.5.1 lib/json_matchers/rspec.rb
json_matchers-0.5.0 lib/json_matchers/rspec.rb
json_matchers-0.4.0 lib/json_matchers/rspec.rb
json-matchers-0.3.1 lib/json_matchers/rspec.rb