Skip to content

Commit

Permalink
Fix checking case sensitivity when value is case insensitive
Browse files Browse the repository at this point in the history
  • Loading branch information
albertyw authored and mcmire committed Oct 9, 2015
1 parent f67183e commit ada9bd3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,14 @@ def validate_case_sensitivity?
if @options[:case_insensitive]
disallows_value_of(swapcased_value, @expected_message)
else
if value == swapcased_value
raise NonCaseSwappableValueError.create(
model: @subject.class,
attribute: @attribute,
value: value
)
end

allows_value_of(swapcased_value, @expected_message)
end
else
Expand Down Expand Up @@ -551,6 +559,33 @@ def class_name
def column_for(scope)
@subject.class.columns_hash[scope.to_s]
end

# @private
class NonCaseSwappableValueError < Shoulda::Matchers::Error
attr_accessor :model, :attribute, :value

def message
Shoulda::Matchers.word_wrap <<-MESSAGE
Your #{model.name} model has a uniqueness validation on :#{attribute} which is
declared to be case-sensitive, but the value the uniqueness matcher used,
#{value.inspect}, doesn't contain any alpha characters, so using it to
to test the case-sensitivity part of the validation is ineffective. There are
two possible solutions for this depending on what you're trying to do here:
a) If you meant for the validation to be case-sensitive, then you need to give
the uniqueness matcher a saved instance of #{model.name} with a value for
:#{attribute} that contains alpha characters.
b) If you meant for the validation to be case-insensitive, then you need to
add `case_sensitive: false` to the validation and add `case_insensitive` to
the matcher.
For more information, please see:
http://matchers.shoulda.io/docs/v#{Shoulda::Matchers::VERSION}/file.NonCaseSwappableValueError.html
MESSAGE
end
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,20 @@

expect(record).to validate_uniqueness
end

context 'given an existing record where the value of the attribute under test is not case-swappable' do
it 'raises a NonCaseSwappableValueError' do
model = define_model_validating_uniqueness(
attribute_type: :string,
validation_options: { case_sensitive: true },
)
record = create_record_from(model, attribute_name => '123')
running_matcher = -> { validate_uniqueness.matches?(record) }

expect(&running_matcher).
to raise_error(described_class::NonCaseSwappableValueError)
end
end
end

context 'when the matcher is qualified with case_insensitive' do
Expand Down

0 comments on commit ada9bd3

Please sign in to comment.