I have a project where heaps of factories are like this:
FactoryGirl.define do
factory :terms_document do
created_by { FactoryGirl.create(:user) }
updated_by { FactoryGirl.create(:user) }
...
end
end
How do I create one user at the start that I can use throughout the factory?
You may add a cache method to the factory file:
def user
@user ||= FactoryGirl.create(:user)
end
FactoryGirl.define do
factory :terms_document do
created_by user
updated_by user
...
end
end
Update : In a case you need different users for different factory instances:
def user(term_document)
@users ||= {}
@users[term_document] ||= FactoryGirl.create(:user)
end
FactoryGirl.define do
factory :terms_document do
...
after(:build) do |term_document|
created_by user(term_document)
updated_by user(term_document)
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.