658 words, 2 mins
FactoryBot的transient用法
用来控制别的属性
factory :user do
transient do
rockstar { true }
end
name { "John Doe#{" - Rockstar" if rockstar}" }
end
create(:user).name
#=> "John Doe - ROCKSTAR"
create(:user, rockstar: false).name
#=> "John Doe"
当使用attributes_for
方法
放在transient
里的属性会被忽略
回调时访问
factory :invoice do
trait :with_amount do
transient do
amount { 1 }
end
after(:create) do |invoice, evaluator|
create :line_item, invoice: invoice, amount: evaluator.amount
end
end
end
create :invoice, :with_amount, amount: 2
关联数据时
不支持这样的transient
关联,所以即使放在transient
里,关联数据也算是正常的数据,non-transient
的数据
factory :post
factory :user do
transient do
post { build(:post) }
end
end
PREVIOUSgithub页面上进行rebase