Rails-如何测试validate_with

问题描述 投票:0回答:1

我具有以下模型,该模型具有对有效代码的自定义验证。

class MyAd < ApplicationRecord
  validates_with CodeValidator
end

和以下类别:

class CodeValidator < ActiveModel::Validator
  def validate(record)
    code = record.ad_code

    return if is_double_id?(code) || is_id?(code)

    if code.blank? || code == 'NO_CODE'
      record.errors[:base] << "A valid code is required."
    end
  end

  def is_double_id?(code)
    code.match(regex here)
  end

  def is_id?(code)
    code.match(regex here)
  end
end

我如何为此编写测试?我是Rails的新手,已经采用了此代码,因此在执行该操作时有些困惑。

这是我开始的内容,但是从阅读中我不确定如何进行测试。 MyAd.new()是否会强制进行验证?

require 'test_helper'

class MyAd < ActiveSupport::TestCase
  setup do
    @ad = MyAd.new(ad_code: 894578945)
  end

  test 'it test code validity' do
    #this is where i need help
  end

任何帮助将不胜感激。

ruby-on-rails ruby ruby-on-rails-5 rails-activerecord
1个回答
1
投票

只需设置一个有效/无效的模型实例,然后调用#valid?触发验证。然后,您可以编写有关errors object的断言。

require 'test_helper'

class MyAd < ActiveSupport::TestCase
  test 'it does not allow a blank code' do
    @ad = MyAd.new(code: '')
    @ad.valid? # fires the validations
    # @fixme your validator should actually be adding errors to :ad_code and not :base 
    assert_includes(@ad.errors[:base], 'A valid code is required.')
  end

  test 'it allows a valid code' do
    @ad = MyAd.new(code: 'SOME VALID CODE')
    @ad.valid? 
    refute_includes(@ad.errors[:base], 'A valid code is required.')
  end
end

不要通过以下方式测试验证:

# as popularized by the Rails tutorial book
assert(model.valid?)
refute(model.valid?)

这种地毯式轰炸方法将一次测试模型上的每个验证,而您实际上只是在测试您的测试设置。

MyAd.new()是否强制执行验证?

没有当您调用#valid?persistence methods#save之类的.create#update时,将执行验证。

© www.soinside.com 2019 - 2024. All rights reserved.