Rails 如何测试 Custom Validator

heroyct · 2019年07月18日 · 2197 次阅读

Custom Validators

具体参考这里 Rails Guide

比如要验证电话号码,可以追加一个 tel_validator

# app/validators/tel_validator.rb

class TelValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors.add(attribute, :tel) unless valid?(value)
  end

  def valid?(tel)
    # validate code
  end
end

如何测试 Custom Validator

1. 创建一个 dummy model

let(:model_class) do
  Struct.new(:tel) do
    include ActiveModel::Validations

    def self.name
      'model'
    end

    validates :tel, tel: true
  end
end

每次都写比较麻烦,可以放到 helper 里面

# spec/support/validator_test_helper.rb

module ValidatorHelper
  def generate_model_class(attr_name, validate_options)
    Struct.new(attr_name) do
      include ActiveModel::Validations

      def self.name
        'model'
      end

      validates attr_name, validate_options
    end
  end
end

RSpec.configure do |config|
  config.include ValidatorHelper, type: :validator
end

2. rspec

# spec/validators/tel_validator_rspec.rb

describe TelValidator, type: :validator do
  let(:model_class) { generate_model_class(:tel, tel: true) }

  it 'valid tel' do
    model = model_class.new '13811112222'
    expect(model.valid?).to eq true
  end
end
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册