简体   繁体   English

为自定义验证器创建测试

[英]Create test for custom validator

Trying to implement a couple tests for my custom validations and I came across this example . 试图为我的自定义验证实施几个测试,然后我遇到了这个示例

My validator looks like this 我的验证器看起来像这样

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

And I've gotten as far as this using the above mentioned example as a guideline. 而且,我已经使用上述示例作为指导来解决这一问题。

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

At this stage I'm getting the error message I am getting is as follows. 在此阶段,我收到的错误消息如下。

rake aborted! 耙子流产了! TypeError: superclass mismatch for class FutureValidator TypeError:类FutureValidator的超类不匹配

I'm not sure how to proceed from here. 我不确定如何从这里继续。

Looks like your model and TestCase have the same class name. 看起来您的模型和TestCase具有相同的类名。 Changing the name of your test should fix the issue. 更改测试名称应该可以解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM