FactoryBot的transient用法

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