Sha256: 2d4a48c992ca2a8c42570ea9ede7b3b91db85d34f0b52eaf6171956fa8c56151

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

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

module ValidationMatcher

  class UnexpectedOptions < RuntimeError

    attr_reader :validator

    def initialze validator
      @validator = validator
    end

    def message
      <<-MSG
        Cannot validate options with custom validator.
        Use `should validate #{ validator.inspect }` (with no options) instead."
      MSG
    end

  end

  RSpec::Matchers.define :validate do |*expected|
    attr_reader :expected_attribute, :expected_options, :expected_validator

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

    match do |actual|
      @expected_options ||= {}
      @expected_validator = expected.first

      validator? or callback?
    end

    def callback_methods
      actual._validate_callbacks.select { |c| c.filter == expected_validator }
    end

    def callback?
      callback = callback_methods.any?
      fail UnexpectedOptions if callback and expected_options.any?
      callback
    end

    def attribute_validators
      expected_attribute ? actual.class.validators_on(expected_attribute) : []
    end

    def validator?
      attribute_validators.any? do |validator|
        validator.kind == expected_validator && validator.options == expected_options
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validation_matcher-3.2.0 lib/validation_matcher.rb