Torbjörn
Torbjörn

Reputation: 5800

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

I've got that simple ActiveModel class holding a string field on which I defined an inclusion validator:

$ 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

Now I'm writing some RSpec test cases, which should represent an always up-to-date docu of that model.

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

How can I automatically generate these three test cases from the list given to the validator?
I know I can get the validator with Person.validators_on(:gender).first, but not how to query that validator instance for the enumerable of the in-option.

The ultimate goal is to replace the three test cases by something like

query_validator_for_in_enum().each do |valid_gender|
  it "allows '#{valid_gender}'" { ... }
end

Rationale: I don't want to create a separate table for 'gender' to workaround this problem.

Upvotes: 1

Views: 458

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

I think you might want to check out shoulda-matchers gem.

Adding this kind of checks would be as easy as:

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

I would create a constant in the model:

GENDERS = %w(male female unknown)

and use it in specs:

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

Upvotes: 3

Related Questions