比如要验证电话号码,可以追加一个 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
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
# 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