Factory Girl: Creating associated records
Asked Answered
F

2

8

I'm trying to do something I think should be fairly simple with Factory Girl and can't quite get it. A user has many stories and I'm testing viewing a user's profile page, which lists their created stories.

I looked up creating associated factories and the docs say I can do something like this:

FactoryGirl.define do

  factory :story do
    title "My Story"
    segments_limit 5
    beginning "Once upon a time"
    completion_status false
    user
  end

  factory :user do
    sequence(:username) { |n| "user-#{n}" }
    sequence(:email) { |n| "user-#{n}@example.com" }
    password "password"
    password_confirmation "password"

    factory :user_with_stories do
      ignore do
        stories_count 5
      end

      after(:create) do |user, evaluator|
        create_list(:story, evaluator.stories_count, user: user)
      end
    end
  end
end

This doesn't seem to work though - when I get into the console and run FactoryGirl.create(:user_with_stories).stories.length, I get an empty array. Am I missing something?

Forestation answered 17/5, 2014 at 21:35 Comment(0)
O
10

you should use after :build and build_list and assign the list to the user's association, like so:

after(:build) do |user, evaluator|
  user.stories << build_list(:story, evaluator.stories_count, user: user)
end
Osteo answered 17/5, 2014 at 22:19 Comment(0)
M
0

Stories are added after creation of user, you need to instantiate the user after creation to see stories attached :

user = FactoryGirl.create(:user_with_stories)
user = User.find user
user.stories.length
Marquesan answered 17/5, 2014 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.