如果您希望來自同一(基地)工廠的記錄具有不同的值,有幾個選項。定義
A)覆蓋屬性
factory :post, aliases: [:approved_post] do
title "A title"
approved true
end
approved_post = create(:approved_post)
unapproved_post = create(:post, approved: false)
B)繼承
factory :post do
title "A title"
factory :approved_post do
approved true
end
factory :unapproved_post do
approved false
end
end
approved_post = create(:approved_post)
unapproved_post = create(:unapproved_post)
C)序列
factory :user do
sequence(:email, 1000) { |n| "person#{n}@example.com" }
end
d)性狀
factory :post do
title "My awesome title"
trait(:approved) { approved true }
trait(:unapproved) { approved false }
trait :with_comments do
after(:create) do |instance|
create_list :comment, 2, post: instance
end
end
factory :approved_post_with_comments, traits: [:approved, :with_comments]
end
approved_post_with_comments = create(:approved_post_with_comments)
unapproved_post_with_no_comments = create(:post, :unapproved, title: "Test")
post_with_title = build(:post)
這些方法可以進行組合。這個例子使用列表和序列對並重寫。
factory :user do
sequence(:username) { |n| "user#{n}" }
date_of_birth Date.today
end
# Build a pair and a list of users.
two_newborns = build_pair(:user)
ten_young_adults = build_list(:user, 10, date_of_birth: 20.years.ago)
# Create a pair and a list of users.
two_young_adults = create_pair(:user, date_of_birth: 20.years.ago)
ten_newborns = create_list(:user, 10)
我更喜歡儘可能使用特質,我覺得它們很靈活。
非常感謝,我接受你的答案在幾分鐘內! ;) – benoitr 2011-04-01 06:25:42
好運@benoitr! – 2011-04-01 06:26:14