如何为 ActiveModel 的包含验证器的每个值生成 RSpec 个测试用例

How to generate RSpec test cases for each value of ActiveModel's Inclusion validator

我有一个简单的 ActiveModel class 持有一个字符串字段,我在该字段上定义了一个 inclusion 验证器:

$ rails generate model Person name:string gender:string
class Person < ActiveRecord::Base
  validates :name, presence: true
  validates :gender, inclusion: { in: %w(male female unknown) }
end

现在我正在编写一些 RSpec 测试用例,它们应该代表该模型的最新文档。

describe Person, type: :model do
  context 'attributes' do
    context 'gender' do
      it 'allows "male"' { ... }
      it 'allows "female"' { ... }
      it 'allows "unknown"' { ... }
    end
  end
end

如何从提供给验证器的列表中自动生成这三个测试用例?
我知道我可以使用 Person.validators_on(:gender).first 获取验证器,但不知道如何查询该验证器实例以获取 in-选项的可枚举。

最终目标是用

之类的东西替换三个测试用例
query_validator_for_in_enum().each do |valid_gender|
  it "allows '#{valid_gender}'" { ... }
end

基本原理:我不想为 'gender' 创建一个单独的 table 来解决这个问题。

我想你可能想看看 shoulda-matchers gem。

添加此类检查非常简单:

it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_inclusion_of(:gender).in_array(%w(male female unknown)) }

我会在模型中创建一个常量:

GENDERS = %w(male female unknown)

并在规范中使用它:

it { is_expected.to validate_inclusion_of(:gender).in_array(Person::GENDERS) }