【发布时间】:2019-10-02 19:31:53
【问题描述】:
我创建了一个自定义验证器,它有自己的特定单元测试来检查它是否有效。
在 was a suggestion 使用 should-matchers 来添加 validates_with 匹配器,这样你就可以这样写:
subject.validates_with(:custom_validator)
完全正确地拒绝了该建议,因为它并没有真正测试模型的行为。
但我的模型有 4 个使用自定义验证器的字段,我希望测试该行为 - 即正在验证这 4 个字段,就像我正在测试它们是否正在验证存在一样:
describe '#attribute_name' do
it { is_expected.to validate_presence_of(:attribute_name) }
end
那么我怎样才能编写一个基本上做同样事情的测试,有点像这样:
describe '#attribute_name' do
it { is_expected.to use_custom_validator_on(:attribute_name) }
end
This question 提出同样的问题,答案建议建立一个测试模型。但是,我的验证器需要一个选项,它的使用方式如下:
\app\models\fund.rb
class Fund < ActiveRecord
validates :ein, digits: { exactly: 9 }
end
所以如果我建立一个测试模型,并按照建议进行测试:
it 'is has correct number of digits' do
expect(build(:fund, ein: '123456789')).to be_valid
end
it 'is has incorrect number of digits' do
expect(build(:fund, ein: '123').to be_invalid
end
我收到RecordInvalid 错误(来自我自己的验证器!哈哈)说我没有为验证器提供所需的选项。该选项被称为“完全”。
1) Fund#ein validates digits
Failure/Error: raise ActiveRecord::RecordInvalid # option :exactly was not provided (incorrect usage)
ActiveRecord::RecordInvalid:
Record invalid
那么 Rspec 不是“看到”模型文件中定义的值“9”吗?
显然,在测试中定义它是没有意义的,因为这是我试图测试的定义行为。可以把它想象成 validates_length_of 测试 { length: x } 选项。
肯定有办法测试这个自定义验证器选项是否设置在模型上?
验证器代码
class DigitsValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.blank?
length = options[:exactly]
regex = /\A(?!0{#{length}})\d{#{length}}\z/
return unless value.scan(regex).empty?
record.errors[attribute] << (options[:message] || error_msg(length))
end
private
def error_msg(length)
I18n.t('activerecord.errors.custom.digits_attr_invalid', length: length) if length
raise ActiveRecord::RecordInvalid # option :exactly was not provided (incorrect usage)
end
end
有趣的旁注
显然,如果我从DigitsValidator 中删除“raise”行,那么两个测试都会成功。我的代码有什么问题我看不到吗?
【问题讨论】:
标签: ruby-on-rails validation rspec ruby-on-rails-5 customvalidator