Saturday 22 June 2013

FactoryGirl with polymorphic associations

Polymorphic associations are very common within a Ruby on Rails app and one of the more popular testing libraries people use is FactoryGirl.

Here we look at how to setup FactoryGirl models to be used in a polymorphic situation.

The issue was first raised on StackOverflow here

For our demonstration, here is a common polymorphic model setup:

FactoryGirl.define do
class Image < ActiveRecord::Base
  mount_uploader :photo, ImageUploader
  belongs_to :imageable, :polymorphic => true

end

class Slideshow < ActiveRecord::Base
  has_many :images, :as => :imageable, :dependent => :destroy

end

class Article < ActiveRecord::Base
  has_many :images, :as => :imageable, :dependent => :destroy

end

And this is how you can build your factories in FactoryGirl to deal with the polymorphic association:

FactoryGirl.define do
  factory :slideshow_image, class: "Image" do
    association :imageable, :factory => :slideshow
    # other attributes for slideshow model
  end
  
  factory :article_image, class: "Image" do
    association :imageable, :factory => :article
    # other attributes for article model
  end
end

This will allow you to call the following:

before(:each) do
  @article_image = FactoryGirl.create(:article_image)
  @article = @article_image.article
end

This provides you with the image, along with the associated article for testing :)

No comments:

Post a Comment