Skip to content

Commit

Permalink
Support enum attributes on validate_absence_of
Browse files Browse the repository at this point in the history
  • Loading branch information
sobrinho committed Oct 14, 2021
1 parent 05a6c37 commit 808be46
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
11 changes: 11 additions & 0 deletions lib/shoulda/matchers/active_model/validate_absence_of_matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ def value
end
elsif array_column?
['an arbitary value']
elsif enum_column?
enum_values.first
else
case column_type
when :integer, :float then 1
Expand Down Expand Up @@ -145,6 +147,15 @@ def array_column?
@subject.class.columns_hash[@attribute.to_s].respond_to?(:array) &&
@subject.class.columns_hash[@attribute.to_s].array
end

def enum_column?
@subject.class.respond_to?(:defined_enums) &&
@subject.class.defined_enums.key?(@attribute.to_s)
end

def enum_values
@subject.class.defined_enums[@attribute.to_s].values
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ def self.available_column_types
end
end

context 'when the column backing the attribute is an enum' do
it 'still works' do
record = active_model_validating_absence_of(:attr) do
enum attr: %w[one two three]
end

expect(record).to validate_absence_of(:attr)
end
end

context 'when used in the negative' do
it 'fails' do
assertion = lambda do
Expand Down Expand Up @@ -295,9 +305,13 @@ def active_model_with(attr, &block)
define_active_model_class('Example', accessors: [attr], &block).new
end

def active_model_validating_absence_of(attr)
def active_model_validating_absence_of(attr, &block)
active_model_with(attr) do
validates_absence_of attr

if block
class_eval(&block)
end
end
end

Expand Down

0 comments on commit 808be46

Please sign in to comment.