为自定义验证器创建测试
Create test for custom validator
尝试为我的自定义验证实施几个测试,我遇到了 。
我的验证器看起来像这样
class FutureValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value == nil
record.errors[attribute] << " can't be nil"
elsif value < Time.now
record.errors[attribute] << (options[:message] || "can't be in the past!")
end
end
end
我已经使用上面提到的示例作为指导,做到了这一点。
require 'test_helper'
class FutureValidatorable
include ActiveModel::Validations
# validates_with FutureValidator
attr_accessor :future
validates :future, future: true
end
class FutureValidator < ActiveSupport::TestCase
future_value = [nil]
def obj; @obj ||= FutureValidatorable.new; end
test 'future validator returns proper error code when nil is passed to it' do
future_value.each do |value|
@obj.value = value
assert_not obj.valid?
end
end
在这个阶段,我收到的错误消息如下。
rake aborted!
TypeError: superclass mismatch for class FutureValidator
我不确定如何从这里开始。
看起来您的模型和 TestCase 具有相同的 class 名称。更改测试名称应该可以解决问题。
尝试为我的自定义验证实施几个测试,我遇到了
我的验证器看起来像这样
class FutureValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value == nil
record.errors[attribute] << " can't be nil"
elsif value < Time.now
record.errors[attribute] << (options[:message] || "can't be in the past!")
end
end
end
我已经使用上面提到的示例作为指导,做到了这一点。
require 'test_helper'
class FutureValidatorable
include ActiveModel::Validations
# validates_with FutureValidator
attr_accessor :future
validates :future, future: true
end
class FutureValidator < ActiveSupport::TestCase
future_value = [nil]
def obj; @obj ||= FutureValidatorable.new; end
test 'future validator returns proper error code when nil is passed to it' do
future_value.each do |value|
@obj.value = value
assert_not obj.valid?
end
end
在这个阶段,我收到的错误消息如下。
rake aborted! TypeError: superclass mismatch for class FutureValidator
我不确定如何从这里开始。
看起来您的模型和 TestCase 具有相同的 class 名称。更改测试名称应该可以解决问题。