FactoryBot工厂中`transient do`块的目的是什么?

在FactoryBot工厂中进行transient do的目的是transient do

我见过很多以下面的东西开头的工厂。

 factory :car do owner nil other_attribute nil end ... 

我在这个博客上找到了一些信息: http : //blog.thefrontiergroup.com.au/2014/12/using-factory-easily-create-complex-data-sets-rails/

但我仍然不完全明白如何以及为什么这样做。 我对FactoryBot的体验很小。

任何有使用FactoryBot经验的人都可以分享一些见解吗?

transient属性允许您传入模型属性的数据。

假设您有一个名为car的模型,其中包含以下属性:

  • 名称
  • 购买价格
  • 模型

您希望在工厂中创建汽车模型时将汽车名称大写。 我们能做的是:

 factory :car do transient do # capitalize is not an attribute of the car capitalize false end name { "Jacky" } purchase_price { 1000 } model { "Honda" } after(:create) do |car, evaluator| car.name.upcase! if evaluator.capitalize end end 

因此,每当您创建汽车工厂并且想要将名称大写时。 你可以做

 car = FactoryGirl.create(:car, capitalize: true) car.name # => "JACKY" 

希望能帮助到你。