Neil
Neil

Reputation: 5178

Factory_girl using #create_list, share the same associations between all created objects

Consider the following associations:

class Blog < ApplicationRecord
  belongs_to :user
  belongs_to :foobar
end

class User < ApplicationRecord
  has_many :blogs
end

class Foobar < ApplicationRecord
  has_many :blogs
end

And here are my factories so far:

FactoryGirl.define do
  factory :blog do
    user
    foobar
  end
end

FactoryGirl.define do
  factory :user do
  end
end

FactoryGirl.define do
  factory :foobar do
  end
end

Here is what I want to do: I want to use create_list to create 5 blogs. However: I want all the blogs to be associated to the same user record and the same foobar record. In other words: I want all 5 blogs to have the exact same user_id and foobar_id.

I did look through the factory_girl docs. This specific scenario is tripping me up.

Upvotes: 3

Views: 964

Answers (1)

Jonathan
Jonathan

Reputation: 945

You should be able to assign the relationships like other attributes. e.g:

user = create(:user)
foobar = create(:foobar)
blogs = create_list(:blog, 5, user: user, foobar: foobar)

Upvotes: 3

Related Questions