Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Girl: Creating associated records

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?

like image 437
Jared Rader Avatar asked May 17 '14 21:05

Jared Rader


1 Answers

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
like image 53
Benj Avatar answered Oct 30 '22 07:10

Benj