title: FactoryGirl and polymorphic associations
body: <h3>The design</h3>
  
  <p>I have a User model that belongs to a profile through a polymorphic association. The reason I chose this design can be found <a href="https://stackoverflow.com/questions/7719600/designing-a-rails-application-single-table-inheritance">here</a>. To summarize, there are many users of the application that have really different profiles.</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    belongs_to :profile, :dependent =&gt; :destroy, :polymorphic =&gt; true
  end
  </code></pre>
  
  <hr>
  
  <pre><code>class Artist &lt; ActiveRecord::Base
    has_one :user, :as =&gt; :profile
  end
  </code></pre>
  
  <hr>
  
  <pre><code>class Musician &lt; ActiveRecord::Base
    has_one :user, :as =&gt; :profile
  end
  </code></pre>
  
  <p>After choosing this design, I'm having a hard time coming up with good tests. Using FactoryGirl and RSpec, I'm not sure how to declare the association the most efficient way.</p>
  
  <h3>First attempt</h3>
  
  <p><strong>factories.rb</strong></p>
  
  <pre><code>Factory.define :user do |f|
    # ... attributes on the user
    # this creates a dependency on the artist factory
    f.association :profile, :factory =&gt; :artist 
  end
  
  Factory.define :artist do |a|
    # ... attributes for the artist profile
  end
  </code></pre>
  
  <p><strong>user_spec.rb</strong></p>
  
  <pre><code>it "should destroy a users profile when the user is destroyed" do
    # using the class Artist seems wrong to me, what if I change my factories?
    user = Factory(:user)
    profile = user.profile
    lambda { 
      user.destroy
    }.should change(Artist, :count).by(-1)
  end
  </code></pre>
  
  <h3>Comments / other thoughts</h3>
  
  <p>As mentioned in the comments in the user spec, using Artist seems brittle. What if my factories change in the future?</p>
  
  <p>Maybe I should use <a href="http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl" rel="noreferrer">factory_girl callbacks</a> and define an "artist user" and "musician user"? All input is appreciated.</p>