简体   繁体   中英

Rails Custom Validators: Testing options

I'm trying to write up a rails gem that involves (amongst other things) some custom model validators...and I'm wondering how to test validation options.

To give an example, I'd like to write an rspec test for which a blank field returns valid if the allow_nil option is true, and invalid otherwise. The code works fine, but I can't think of an elegant way to test it. The code itself:

Module ActiveModel
  module Validations
    module ThirstyVals
      class ValidatePrime < EachValidator
        # Validate prime numbers
        def validate_each(record, attr_name, value)
          return if options[:allow_nil] && value.strip.length == 0

          # Other validation code here
          # ...
        end
      end
    end
  end
end

I'm currently testing through a dummy project, which is fine, but the only way I can think of to test the :allow_nil option is to write up a new attribute with :allow_nil set, and verify its functionality...which seems both excessive and pretty inelegant. There must be a more graceful way - any ideas appreciated. (Other tests below for posterity)

# ...
before(:each) do
  @entry = Entry.new
end

describe "it should accept valid prime numbers" do
  ['7', '13', '29'].each do |n|
    @entry.ticket = n
    @entry.valid?('ticket').should be_true
  end
end

describe "it should reject non-prime numbers" do
  ['4', '16', '33'].each do |n|
    @entry.ticket = n
    @entry.valid?('ticket').should be_false
  end
end

have you considered testing the validator in isolation like so:

in validate_prime_spec.rb

require path_to_validator_file

describe ActiveModel::Validations::ThirstyVals::ValidatePrime do
  context :validate_each do
    it 'should do some stuff' do
      subject.validate_each(record, attr_name, value).should #some expectation
    end
  end
end

then may I suggest that you need not test the allow_nil functionality of Rails validations due to the fact that it is already tested in Rails? (see: activemodel/test/cases/validations/inclusion_validation_test.rb line 44 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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