ruby on rails - How to generate RSpec test cases for each value of ActiveModel's Inclusion validator -
i've got simple activemodel class holding string field on defined 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 rspec test cases, should represent up-to-date docu of model.
describe person, type: :model context 'attributes' context 'gender' 'allows "male"' { ... } 'allows "female"' { ... } 'allows "unknown"' { ... } end end end
how can automatically generate these 3 test cases list given validator?
know can validator person.validators_on(:gender).first
, not how query validator instance enumerable of in
-option.
the ultimate goal replace 3 test cases like
query_validator_for_in_enum().each |valid_gender| "allows '#{valid_gender}'" { ... } end
rationale: don't want create separate table 'gender' workaround problem.
i think might want check out shoulda-matchers gem.
adding kind of checks easy as:
it { is_expected.to validate_presence_of(:name) } { is_expected.to validate_inclusion_of(:gender).in_array(%w(male female unknown)) }
i create constant in model:
genders = %w(male female unknown)
and use in specs:
it { is_expected.to validate_inclusion_of(:gender).in_array(person::genders) }
Comments
Post a Comment