Skip to content

Commit

Permalink
Fixing validation in has_one when document is nil
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Dec 12, 2009
1 parent 724a023 commit 5299039
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 8 deletions.
5 changes: 5 additions & 0 deletions lib/mongoid/associations/has_one.rb
Expand Up @@ -43,6 +43,11 @@ def method_missing(name, *args)
@document.send(name, *args)
end

# Need to override here for when the underlying document is nil.
def valid?
@document ? @document.valid? : false
end

class << self
# Preferred method of instantiating a new +HasOne+, since nil values
# will be handled properly.
Expand Down
32 changes: 32 additions & 0 deletions spec/unit/mongoid/associations/has_one_spec.rb
Expand Up @@ -129,4 +129,36 @@

end

describe "#valid?" do

context "when the document is nil" do

before do
@document = stub(:attributes => {})
@options = Mongoid::Associations::Options.new(:name => :name)
@association = Mongoid::Associations::HasOne.instantiate(@document, @options)
end

it "returns false" do
@association.valid?.should be_false
end

end

context "when the document is not nil" do

before do
@document = stub(:attributes => { :name => { :first_name => "Test" } }, :update => true)
@options = Mongoid::Associations::Options.new(:name => :name)
@association = Mongoid::Associations::HasOne.instantiate(@document, @options)
end

it "validates the document" do
@association.valid?.should be_true
end

end

end

end
32 changes: 24 additions & 8 deletions spec/unit/mongoid/document_spec.rb
Expand Up @@ -807,16 +807,32 @@

context "when association is a has_one" do

it "fails when the association fails validation" do
Person.class_eval do
validates_associated :name
context "when the associated is not nil" do

it "fails when the association fails validation" do
Person.class_eval do
validates_associated :name
end
Name.class_eval do
validates_presence_of :first_name
end
@person.name = Name.new
@person.valid?.should be_false
@person.errors.on(:name).should_not be_nil
end
Name.class_eval do
validates_presence_of :first_name

end

context "when the associated is nil" do

it "fails when the association fails validation" do
Person.class_eval do
validates_associated :name
end
@person.valid?.should be_false
@person.errors.on(:name).should_not be_nil
end
@person.name = Name.new
@person.valid?.should be_false
@person.errors.on(:name).should_not be_nil

end

end
Expand Down

0 comments on commit 5299039

Please sign in to comment.