From b3113117bd9bc445f297e172abebdaebb791147d Mon Sep 17 00:00:00 2001 From: Florence Foo Date: Mon, 2 Mar 2015 09:39:44 +1100 Subject: [PATCH] validate_after_scope_change? use compact before retrieving max Otherwise produces error "ArgumentError: comparison of NilClass with String failed" if the resultant contains a combinations of strings and nils. --- NEWS.md | 4 ++++ .../active_record/validate_uniqueness_of_matcher.rb | 2 +- .../validate_uniqueness_of_matcher_spec.rb | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 23da3e14..cc37e379 100644 --- a/NEWS.md +++ b/NEWS.md @@ -55,6 +55,9 @@ * Fix `permit` so that it does not break the functionality of ActionController::Parameters#require. ([#648], [#675]) +* Fix `validate_uniqueness_of` + `scoped_to` so that it does not raise an error + if a record exists where the scoped attribute is nil. ([#677]) + ### Features * Add `on` qualifier to `permit`. This allows you to make an assertion that @@ -71,6 +74,7 @@ [#607]: https://github.com/thoughtbot/shoulda-matchers/pull/607 [#648]: https://github.com/thoughtbot/shoulda-matchers/pull/648 [#675]: https://github.com/thoughtbot/shoulda-matchers/pull/675 +[#677]: https://github.com/thoughtbot/shoulda-matchers/pull/677 # 2.8.0 diff --git a/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb b/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb index dd4283bf..8ab02525 100644 --- a/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb +++ b/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb @@ -386,7 +386,7 @@ module Shoulda else all_records = @subject.class.all @options[:scopes].all? do |scope| - previous_value = all_records.map(&scope).max + previous_value = all_records.map(&scope).compact.max next_value = if previous_value.blank? diff --git a/spec/unit/shoulda/matchers/active_record/validate_uniqueness_of_matcher_spec.rb b/spec/unit/shoulda/matchers/active_record/validate_uniqueness_of_matcher_spec.rb index 32cd7b82..48747231 100644 --- a/spec/unit/shoulda/matchers/active_record/validate_uniqueness_of_matcher_spec.rb +++ b/spec/unit/shoulda/matchers/active_record/validate_uniqueness_of_matcher_spec.rb @@ -390,6 +390,17 @@ describe Shoulda::Matchers::ActiveRecord::ValidateUniquenessOfMatcher, type: :mo array: true end end + + context "when an existing record that is not the first has a nil value for the scoped attribute" do + it 'still works' do + model = define_model_validating_uniqueness(scopes: [:scope]) + create_record_from(model, scope: 'some value') + create_record_from(model, scope: nil) + record = build_record_from(model, scope: 'a different value') + + expect(record).to validate_uniqueness.scoped_to(:scope) + end + end end context 'when the model has a case-sensitive validation' do