FactoryBot工厂中的"transient do"块的目的是什么? [英] What is the purpose of a `transient do` block in FactoryBot factories?

查看:51
本文介绍了FactoryBot工厂中的"transient do"块的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

transient do在FactoryBot工厂中的用途是什么?

What is the purpose of transient do in FactoryBot factories?

我已经看到很多工厂都以下面的形式开始.

I've seen a lot of factories that begin with something like below.

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

我在此博客上找到了一些信息:

I've found some information on this blog: http://blog.thefrontiergroup.com.au/2014/12/using-factorygirl-easily-create-complex-data-sets-rails/

但是我仍然不完全了解如何以及为什么这样做.我对FactoryBot的经验很少.

But I still don't fully understand how and why to do this. My experience with FactoryBot is minimal.

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

Could anyone with some experience using FactoryBot share some insight?

推荐答案

transient属性允许您传入模型中不是属性的数据.

transient attributes allow you to pass in data that isn’t an attribute on the model.

假设您有一个名为car的模型,该模型具有以下属性:

Say you have a model called car with the following attributes:

  • 名称
  • 购买价格
  • 模型

在工厂中创建汽车模型时,要大写汽车名称.我们可以做的是:

You want to capitalize the name of the car when you create the car model in the factory. What we can do is:

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

因此,每当您创建汽车制造厂并希望将名称大写时.您可以

Hence, whenever you create the car factory and you want to capitalize the name. You can do

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

希望有帮助.

这篇关于FactoryBot工厂中的"transient do"块的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆