In Rails (3.0) test code, I've cloned an object so I can clobber it for validation testing without changing the original. If I have called assert(original.valid?) before cloning, then the clone passes the validates_presence_of test even after I have set member_id value to nil.
The two tests below illustrate this. In test one, the clone is created before the original ("contact") is validated. Clone correctly fails the validation when member_id is missing. Assertion C succeeds.
In test two, the clone is created after the original is validated. Even though clone.member_id is set to nil, it passes the validation. In other words, assertion 2C fails. The only difference between the tests is the order of the two lines:
cloned = contact.clone
assert(contact.valid?,"A")
What is going on here? Is this normal Ruby behavior re: cloning that I just don't understand?
test "clone problem 1" do
contact = Contact.new(:member_id => 1)
cloned = contact.clone
assert(contact.valid?,"A")
cloned.member_id = nil
assert(!cloned.valid?,"C")
end
test "clone problem 2" do
contact = Contact.new(:member_id => 1)
assert(contact.valid?,"2A")
cloned = contact.clone
cloned.member_id = nil
assert(!cloned.valid?,"2C")
end