Factory Girl: creating related records

I'm trying to do something that, in my opinion, should be fairly simple with Factory Girl and not be able to get it. The user has a lot of stories, and I'm testing a user profile page that lists their created stories.

I was looking for creating linked factories and the docs say that 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 does not seem to work - when I enter the console and run FactoryGirl.create(:user_with_stories).stories.length , I get an empty array. Did I miss something?

+6
source share
2 answers

you should use after :build and build_list and assign the list to user associations, for example:

 after(:build) do |user, evaluator| user.stories << build_list(:story, evaluator.stories_count, user: user) end 
+4
source

Stories are added after the user is created, you need to create a user instance after creation to see the attached stories:

 user = FactoryGirl.create(:user_with_stories) user = User.find user user.stories.length 
+1
source

Source: https://habr.com/ru/post/969445/


All Articles