title: FactoryGirl change attribute structure in factory
body: <p>FactoryGirl 4.5.0</p>
  
  <p>How do I change the structure of the passed attributes? For example, when working with a large set of existing tests, when serialising existing fields it is desirable for the factory to use the old attributes to make the new models.</p>
  
  <h2>Explanation</h2>
  
  <p>Given the model Emerald:</p>
  
  <pre><code># app/models/emerald.rb
  class Emerald &lt; ActiveRecord::Base
    validates_presence_of :name, :size, :shinyness, :color
  end
  </code></pre>
  
  <p>The factory for Emerald:</p>
  
  <pre><code># spec/factories/emerald_spec.rb
  FactoryGirl.define do
    factory :emerald do
      sequence(:name) {|n| "Emerald #{n} name"}
      size: 12
      shinyness: 34
      color: 'Dark Green'
    end
  end
  </code></pre>
  
  <p>And many rspec tests which do something like:</p>
  
  <pre><code>let(:shiny_emerald) { create(:emerald, attributes: { name: 'Shiny', shinyness: 99 })}
  let(:big_emerald)   { create(:emerald, attributes: { name: 'Big', size: 888 })}
  </code></pre>
  
  <p>When serialising some fields on Emerald we get</p>
  
  <pre><code># app/models/emerald.rb
  class Emerald &lt; ActiveRecord::Base
  
    serialize :emerald_properties, Hash
  
    validates_presence_of :name
    validates :emerald_properties, emerald_properties: true # This is a custom validator
  
    def size
      emerald_properties[:size]
    end
    def size=(value)
      emerald_properties[:size] = value
    end
    def shinyness
      emerald_properties[:shinyness]
    end
    def shinyness=(value)
      emerald_properties[:shinyness] = value
    end
    def colour
      emerald_properties[:colour]
    end
    def colour=(value)
      emerald_properties[:colour] = value
    end
  end
  </code></pre>
  
  <p>"Why don't you *<em>do it a different way which might be possible in the limited scope of this example but doesn't apply to any person who might search for this*</em>" aside, what should be done in the factory to allow the existing tests to remain unchanged?</p>
  
  <p>The model still allows you to <code>emerald.size</code> instead of forcing the use of <code>emerald.emerald_properties[:size]</code>, I am aiming to achieve the same thing for wielding the factory.</p>
  
  <p>It is a lot of work to do:</p>
  
  <pre><code>let(:big_emerald) { create(:emerald, attributes: { name: 'Big', emerald_properties{ size: 888 }})}
  </code></pre>
  
  <p>everywhere, aiming to keep</p>
  
  <pre><code>let(:big_emerald) { create(:emerald, attributes: { name: 'Big', size: 888 })}
  </code></pre>
  
  <p>and adjust it inside the factory.</p>
  
  <p>So far I have:</p>
  
  <pre><code>FactoryGirl.define do
    factory :emerald do
      sequence(:name) {|n| "Emerald #{n} name"}
      emerald_properties ({ {size: 12, shinyness: 34, color: 'Dark Green'}.merge(attributes.slice(*[:size, :shinyness, :color])) })
    end
  end
  </code></pre>
  
  <p>but it does not work</p>