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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With