This page has notes from ThoughtBot about how to do Factory Girl testing setup.
Thanks to Dan Croak, author of Factory Girl, for providing these ideas.
Related: Factory Girl Testing Speed By ThoughtBot
Suppose you have a factory like this:
user = Factory(:user)
To create 3 users, we call the factory in a loop like this:
users = 3.times { Factory(:user) }
Do it in FactoryGirl's after_create on the belonging object.
Suppose you have a class "User" that belongs to a "Team".
To create a team with 3 users:
Factory.define :team_with_three_users do |team|
team.after_create do |team_after_create|
3.times { Factory(:user, :team => team_after_create) }
end
end
Write a helper method. Suppose you have a User class and you want to randomly pick a team from among many teams.
# in test/factories.rb or spec/factories.rb
def teams
@teams ||= 3.times { Factory(:team) }
end
# Now your user factory can call the helper
Factory.define :user |user|
user.after_create do |user_after_create|
user_after_create.team = teams.sample
end
end
Given /^typical (\w+)/ do |name|
Factory(name)
end
Given a typical user. Given a typical team.