What is the purpose of a `transient do` block in FactoryBot factories?

tim_xyz picture tim_xyz · Jul 25, 2016 · Viewed 18k times · Source

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/

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

Could anyone with some experience using FactoryBot share some insight?

Answer

Sam Kah Chiin picture Sam Kah Chiin · Jan 13, 2017

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

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

  • name
  • purchase_price
  • model

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"

Hope it helps.