# Problems testing a method to clone associations

**URL:** <https://www.ruby-forum.com/t/problems-testing-a-method-to-clone-associations/189735>\
**Category:** Rails\
**Created:** [June 6, 2010, 7:40pm UTC](https://www.ruby-forum.com/t/problems-testing-a-method-to-clone-associations/189735 "2010-06-06T19:40:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ginty](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f0a364/32.png) [@ginty](https://www.ruby-forum.com/u/ginty)\
**Post date:** [June 6, 2010, 7:40pm UTC](https://www.ruby-forum.com/t/problems-testing-a-method-to-clone-associations/189735/1 "2010-06-06T19:40:44Z")

</div>

I’ve got a method to ‘deep clone’ an object, basically to clone it  
plus all of its associations.

Here is the code:

def deep\_clone  
clone = self.clone  
%w[phone\_numbers addresses websites emails].each do |assoc|  
clone.send("#{assoc}=", self.send(assoc).collect { |obj|  
obj.clone })  
end  
clone  
end

This works perfectly in practice, the problem is that it is failing  
during test, like so:

clone = orig.deep\_clone  
clone.save  
clone.emails.size.should == orig.emails.size # This passes  
orig.emails.each { |e| clone.email\_ids.should\_not include e.id } #  
This fails

The fail is because the exact same email objects are assigned to both  
the orig and the clone.  
Looking at it in debug I can see that orig.emails and clone.emails (or  
any other association for that matter) are tied together, such that  
changing one mirrors the exact same change in the other.  
I can also see that the clone is indeed a different object instance  
from orig, it has a different id, and therefore clone.emails= should  
not affect orig.emails.

Is this a bug or is there some nuance of the test environment I am  
missing?

I am using the latest Rails 3 here, so I suspect it could be a genuine  
bug…
