Skip to content

Commit

Permalink
Allow beginless and endless ranges in validates_inclusion_of (#1615)
Browse files Browse the repository at this point in the history
  • Loading branch information
pjpires committed Feb 23, 2024
1 parent e2a6677 commit a078b46
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 9 deletions.
28 changes: 20 additions & 8 deletions lib/shoulda/matchers/active_model/validate_inclusion_of_matcher.rb
Expand Up @@ -309,8 +309,8 @@ def in_array(array)

def in_range(range)
@range = range
@minimum = range.first
@maximum = range.max
@minimum = minimum_range_value
@maximum = maximum_range_value
self
end

Expand Down Expand Up @@ -400,6 +400,18 @@ def does_not_match?(subject)

private

def minimum_range_value
@range.begin
end

def maximum_range_value
if @range.exclude_end?
@range.end ? (@range.end - 1) : nil
else
@range.end
end
end

def matches_for_range?
disallows_lower_value &&
allows_minimum_value &&
Expand Down Expand Up @@ -441,27 +453,27 @@ def disallows_lower_value
end

def allows_minimum_value
allows_value_of(@minimum, @low_message)
@minimum.nil? || allows_value_of(@minimum, @low_message)
end

def disallows_minimum_value
disallows_value_of(@minimum, @low_message)
@minimum.nil? || disallows_value_of(@minimum, @low_message)
end

def allows_maximum_value
allows_value_of(@maximum, @high_message)
@maximum.nil? || allows_value_of(@maximum, @high_message)
end

def disallows_maximum_value
disallows_value_of(@maximum, @high_message)
@maximum.nil? || disallows_value_of(@maximum, @high_message)
end

def allows_higher_value
allows_value_of(@maximum + 1, @high_message)
@maximum.nil? || allows_value_of(@maximum + 1, @high_message)
end

def disallows_higher_value
disallows_value_of(@maximum + 1, @high_message)
@maximum.nil? || disallows_value_of(@maximum + 1, @high_message)
end

def allows_all_values_in_array?
Expand Down
2 changes: 1 addition & 1 deletion lib/shoulda/matchers/util.rb
Expand Up @@ -66,7 +66,7 @@ def self.inspect_values(values)
end

def self.inspect_range(range)
"#{inspect_value(range.first)} to #{inspect_value(range.last)}"
"#{inspect_value(range.begin)} to #{inspect_value(range.end)}"
end

def self.inspect_hash(hash)
Expand Down
Expand Up @@ -572,6 +572,22 @@ def configure_validation_matcher(matcher)
expect_to_match_on_values(builder, possible_values)
end

it 'matches given a beginless range that covers the possible values' do
builder = build_object_allowing(possible_values)
expect_to_match_on_values(
builder,
Range.new(nil, possible_values.last),
)
end

it 'matches given a endless range that covers the possible values' do
builder = build_object_allowing(possible_values)
expect_to_match_on_values(
builder,
Range.new(possible_values.first, nil),
)
end

it 'does not match given a range whose start value falls outside valid range' do
builder = build_object_allowing(possible_values)
expect_not_to_match_on_values(
Expand Down

0 comments on commit a078b46

Please sign in to comment.