Report abuse

# http://blog.trapdoor1.net/2008/07/09/quick-testing-of-activerecord-validations-in-rspec/
class ValidateWithExactly
  def initialize(attrs)
    @attrs = attrs
  end

  def matches?(object)
    @object = object

    unless @object.valid?
      @failure = "#{@object} should be valid with specified attributes #{@attrs.keys.inspect}, but isn't."
      return(false)
    end

    @attrs.each_pair do |attribute, value|
      new_attributes = @attrs.reject{ |k, v| k == attribute.to_sym }
      test_object = @object.class.new(new_attributes)

      if test_object.valid?
        @failure = "Removing attribute #{attribute.inspect} should invalidate the object, but doesn't."
        return(false)
      end
    end

    return(true)
  end

  def failure_message
    @failure
  end
end

def validate_with_exactly(attrs)
  ValidateWithExactly.new(attrs)
end