Sha256: af30bf4752a26d03f4dc00824be87e8beb8646338710bc3c6f4f6aebdf694f13

Contents?: true

Size: 1.83 KB

Versions: 2

Compression:

Stored size: 1.83 KB

Contents

require 'validation_matcher/version'
require 'validation_matcher/hash_diff'
require 'rspec/expectations'

module ValidationMatcher

  using HashDiff

  RSpec::Matchers.define :validate do |kind|

    chain(:of)   { |field| @field            = field }
    chain(:with) { |hash|  @expected_options = hash }

    description do
      msg  = "validate the #{ kind } of #{ @field.inspect }"
      msg << " with options: #{ @expected_options.inspect }" if @expected_options
      @expected_options = nil # for some reason this appears to be cached between runs?
      msg
    end

    failure_message do
      "Expected #{ described_class } to validate the #{ kind } of #{ @field.inspect } #{ diff_with }"
    end

    failure_message_when_negated do
      "Expected #{ described_class } not to validate the #{ kind } of #{ @field.inspect } #{ diff_with }"
    end

    def expected_options
      @expected_options || {}
    end

    def validator
      @validator ||= actual.class.validators_on(@field).detect { |v| expected == v.kind }
    end

    def validator_options
      @validator_options ||= validator.options rescue {}
    end

    def diff_with?
      # if validator_options is empty and @expected_options is not, there is a problem
      # if @expected_options is empty and validator_options is not, there is a problem
      # if neither is empty diff_with them, if there's a diff_with, there is a problem

      return true if expected_options.present? ^ validator_options.present?
      return true if validator_options.diff_with(expected_options).present?
      false
    end

    def diff_with
      return '' unless diff_with?
      str  = "\n expected options: #{ expected_options.inspect }"
      str << "\n actual options: #{ validator_options.inspect }"
      str
    end

    match do |actual|
      validator.present? and not diff_with?
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
validation_matcher-3.0.1 lib/validation_matcher.rb
validation_matcher-3.0.0 lib/validation_matcher.rb