How to generate multiple asscoated records for the same parent record in factory_girl?
Here is the definition for model user and user_level. A user has many user levels and a user level belongs to a user.
Factory.define :user do |user|
user.name 开发者_开发问答 "Test User"
user.email "test@test.com"
user.password "password1"
user.password_confirmation "password1"
user.status "active"
user.user_type "employee"
end
Factory.define :user_level do |level|
level.role "sales"
level.position "member"
level.team 1
level.association :user
end
@user_level = Factory(:user_level) generates one user_level record and its parent record in users table. What do I do if I need generate 2 user level records for one parent user record?
Any thoughts? thanks.
You can specify the user first, and then pass the same user to each factory create call:
@user = Factory(:user)
@user_level = Factory(:user_level, :user => @user)
@user_level2 = Factory(:user_level, :user => @user)
To do a quick sanity check, do an assert equal
(confirms it's the same object)
@user_level.user.should equal @user_level2.user
精彩评论