thoughtbot/factory_girl — pull request #588 by greyblake (2013-12-11 14:08:25+00:00)
Title: Fix memory leak: do not add trait duplications to @defined_traits

Each call of `FactoryGir.build()` with trait leads to adding an instance of `FactoryGirl::Trait` to `@defined_traits` array. After ~1 hour of running tests in huge application it results into serious memory leaks (in our case it took over 14Gb of RAM, when usually 1Gb is enough) and specs never end, seems almost all the time are used by GC.

### How to Reproduce:

I've created a demo application for it: https://github.com/greyblake/factory_memory_leak

In short:
* Create a model `rails g user login:string name:string`
* Create a factory:

```ruby
factory :user do
login "hack68"

trait :with_name do
name "Mr. Smith"
end
end
```
* Create a test to demonstrate the leak:

```ruby
require 'test_helper'

class UserTest < ActiveSupport::TestCase
test "the memory leak" do
10.times do |index|
puts "\nIteration: #{index}"

ObjectSpace.each_object(Array) do |array| if array.last.is_a?(FactoryGirl::Trait) && array.size > 1
puts "Traits: #{array.size}"
puts "Unique traits: #{array.uniq.size}"
end
end

FactoryGirl.build(:user, :with_name)
end
end
end
```
* Run the test:

```
~/dev/work/tmx/factory_memory_leak[master]$ rake test
Run options:

# Running tests:

[1/1] UserTest#test_the_memory_leak
Iteration: 0

Iteration: 1

Iteration: 2
Traits: 2
Unique traits: 1

Iteration: 3
Traits: 3
Unique traits: 1

Iteration: 4
Traits: 4
Unique traits: 1

Iteration: 5
Traits: 5
Unique traits: 1

Iteration: 6
Traits: 6
Unique traits: 1
```

So, every call of `build` increments the trait array by `1` (at least in this simple app). Using [ruby-mass](https://github.com/archan937/ruby-mass/) I found out that the array is `defined_tratis` proprety of `FactoryGirl::Definition`

### Environment

* Ruby 1.9.3 / 2.0.0 / 2.1.0
* Rails 3.2.15
* FactoryGirl: 4.3.0
* OS: Linux Debian Squeeze