From cb02954e57b7874e556f5004af35d4dd2dd3d3ef Mon Sep 17 00:00:00 2001 From: Ian Lesperance Date: Wed, 27 Jun 2012 17:57:13 -0700 Subject: [PATCH] Restore uniqueness scope values after verifying each scope. A test for a validation with multiple scopes would always pass as long as there was a validation with the first scope. Subsequent scopes would pass verification because the first scope value had already been made unique. --- .../validate_uniqueness_of_matcher.rb | 2 ++ .../validate_uniqueness_of_matcher_spec.rb | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb b/lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb index 8ebdb1da..4850b00e 100644 --- a/lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb +++ b/lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb @@ -133,6 +133,8 @@ module Shoulda # :nodoc: @subject.send("#{scope}=", next_value) if allows_value_of(existing_value, @expected_message) + @subject.send("#{scope}=", previous_value) + @negative_failure_message << " (with different value of #{scope})" true diff --git a/spec/shoulda/active_model/validate_uniqueness_of_matcher_spec.rb b/spec/shoulda/active_model/validate_uniqueness_of_matcher_spec.rb index d4a3f0bc..e77cec91 100644 --- a/spec/shoulda/active_model/validate_uniqueness_of_matcher_spec.rb +++ b/spec/shoulda/active_model/validate_uniqueness_of_matcher_spec.rb @@ -66,11 +66,12 @@ describe Shoulda::Matchers::ActiveModel::ValidateUniquenessOfMatcher do before do @model = define_model(:example, :attr => :string, :scope1 => :integer, - :scope2 => :integer) do - attr_accessible :attr, :scope1, :scope2 + :scope2 => :integer, + :other => :integer) do + attr_accessible :attr, :scope1, :scope2, :other validates_uniqueness_of :attr, :scope => [:scope1, :scope2] end.new - @existing = Example.create!(:attr => 'value', :scope1 => 1, :scope2 => 2) + @existing = Example.create!(:attr => 'value', :scope1 => 1, :scope2 => 2, :other => 3) end it "should pass when the correct scope is specified" do @@ -81,10 +82,18 @@ describe Shoulda::Matchers::ActiveModel::ValidateUniquenessOfMatcher do @existing.should validate_uniqueness_of(:attr).scoped_to(:scope1, :scope2) end - it "should fail when a different scope is specified" do + it "should fail when too narrow of a scope is specified" do + @model.should_not validate_uniqueness_of(:attr).scoped_to(:scope1, :scope2, :other) + end + + it "should fail when too broad of a scope is specified" do @model.should_not validate_uniqueness_of(:attr).scoped_to(:scope1) end + it "should fail when a different scope is specified" do + @model.should_not validate_uniqueness_of(:attr).scoped_to(:other) + end + it "should fail when no scope is specified" do @model.should_not validate_uniqueness_of(:attr) end