Richlewis
Richlewis

Reputation: 15374

How to create a valid factory with a has_many association

I have been trying to get this to work looking at the official documentation, this blog post and have looked at examples on here. Whatever I try I get errors.

I am looking for a working example to see how the test is structured; I am using Factory Girl 4.4.1 and Rspec 3.

The only way I have managed to create a valid object is by doing this, but it's not the correct way to build my object as I want to still run validation on the animal model first and then animal_image.

FactoryGirl.define do
  factory :animal_image do
   animal_id 1
   image { File.open("#{Rails.root}/spec/fixtures/yp2.jpg") }
 end 
end

file = FactoryGirl.create(:animal_image)
#<AnimalImage id: 101, animal_id: 1, image: "yp2.jpg", created_at: "2014-10-14 10:08:55", updated_at: "2014-10-14 10:08:55">

My models

class Animal < ActiveRecord::Base
  has_many :animal_images, dependent: :destroy
end

class AnimalImage < ActiveRecord::Base
  belongs_to :animal
end

Upvotes: 0

Views: 101

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Try this:

FactoryGirl.define do
  factory :animal do

    ignore do
      images_count 5
    end

    after(:create) do |animal, evaluator|
      create_list(:animal_image, evaluator.images_count, animal: animal)
    end

  end 
end

FactoryGirl.define do
  factory :animal_image do

    image { File.open("#{Rails.root}/spec/fixtures/yp2.jpg") }

  end 
end

a = FactoryGirl.create(:animal)
a.animal_images.count
=> 5

a = FactoryGirl.create(:animal, images_count: 1)
a.animal_images.count
=> 1

More information here

Upvotes: 1

Related Questions