FactoryBot Fields Can Be Defined Relative to Each Other

In FactoryBot, you can reference fields of a factory when defining other fields of the same factory. That helps reduce code duplication!

For example, suppose you have a Person class that has the fields first_name and full_name. You can define the Person factory so that full_name will reference first_name.

That looks like this:

factory :person do
  sequence(:first_name) { |n| "foo#{n}"}
  full_name { first_name.capitalize + " Smith" }
end

This was tricky to figure out, so I’m jotting it down here!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: