user3206440
user3206440

Reputation: 5049

factory_girl - associations , polymorphic in rails

I have the following rails models relations for which the factory girl factory definition is not getting right and giving errors.

class MediaFile < ActiveRecord::Base
  belongs_to :admin
end

class MediaFileMapping < ActiveRecord::Base
  belongs_to :media_file
  belongs_to :admin
  belongs_to :mediable, :polymorphic => true
end

class Image < MediaFile
  has_attached_file :media
  # and other things
end

class ImageMapping < MediaFileMapping
end

class Fruit < ActiveRecord::Base      
  belongs_to :product
  has_many :image_mappings, :as => :mediable
  has_many :images, :class_name => "Image", :through => :image_mappings, :source => :media_file

# and other things here
end

class Product < ActiveRecord::Base      
  has_many :fruits, :dependent => :destroy
# other things here    
end

I'm struggling with writing factories for this. Here is the last attempt which give error

Factory definitions attempted are as follows

FactoryGirl.define do     
        factory :product do
            fruit
        end

        factory :fruit do
            association :image_mapping, factory: :media_file_mapping
            association :image
        end

        factory :image, class: Image, parent: :media_file do
        end

        factory :image_mapping, class: ImageMapping, parent: :media_file_mapping do
        end

        factory :admin do
        end

        factory :media_file do
            association :admin
        end

    factory :media_file_mapping do
        media_file
        admin
    end

end

This is giving the following error on creating a new Product via factory

undefined method `image_mapping=' for #<Fruit:0xbcb8bfc> (NoMethodError)

Any directions to fix the definition of factory would be helpful.

Upvotes: 0

Views: 661

Answers (1)

spiria
spiria

Reputation: 106

The Fruit Factory is not correct.

The syntax: association :image_mapping, factory: :media_file_mapping can be used for belongs_to associations.

When you are dealing with a has_many association(this case) you need to manually add the associated records in the factory definition. An example:

    factory :fruit do
        after(:create) do |fruit|
            fruit.image_mappings << FactoryGirl.create(:image_mapping)
            fruit.images << FactoryGirl.create(:image)
        end
        fruit.save
    end

You also probably should move the fruit factory so that it is below the image_mapping and image factories. This way those factories will be defined when the fruit factory is called.

Upvotes: 2

Related Questions