From d6b10f92acca6945fa330b2372e54a984118e3ba Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Mon, 12 Dec 2011 12:19:55 -0700 Subject: [PATCH] added :context option to validates_associated --- lib/mongo_mapper/plugins/validations.rb | 2 +- test/functional/test_validations.rb | 33 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/mongo_mapper/plugins/validations.rb b/lib/mongo_mapper/plugins/validations.rb index d7c4b9a2a..5a973a18d 100644 --- a/lib/mongo_mapper/plugins/validations.rb +++ b/lib/mongo_mapper/plugins/validations.rb @@ -68,7 +68,7 @@ def scope_conditions(instance) class AssociatedValidator < ::ActiveModel::EachValidator def validate_each(record, attribute, value) - if !Array.wrap(value).all? { |c| c.nil? || c.valid? } + if !Array.wrap(value).all? { |c| c.nil? || c.valid?(options[:context]) } record.errors.add(attribute, :invalid, :message => options[:message], :value => value) end end diff --git a/test/functional/test_validations.rb b/test/functional/test_validations.rb index b091360d8..814e36cc7 100644 --- a/test/functional/test_validations.rb +++ b/test/functional/test_validations.rb @@ -350,6 +350,39 @@ def action_present doc.children.build doc.should have_error_on(:children, 'are invalid') end + + end + + context "validating associated docs with custom context" do + setup do + @child_class = EDoc do + key :name + + validates_length_of :name, :minimum => 5, :on => :custom_context + end + + @root_class = Doc { } + @root_class.many :children, :class => @child_class + @root_class.validates_associated :children, :context => :custom_context + end + + should "pass if there are no associated docs" do + doc = @root_class.new + doc.valid?(:custom_context).should be_true + end + + should "pass if the associated doc is valid" do + doc = @root_class.new + doc.children.build(:name => 'George') + doc.valid?(:custom_context).should be_true + end + + should "fail if the associated doc is invalid" do + doc = @root_class.new + doc.children.build(:name => 'Bob') + doc.valid?(:custom_context).should_not be_true + end + end # context "validates uniqueness of with :unique shortcut" do # should "work" do