In a factory_bot factory for a merch-store order, how do traits, sequences, transient attributes and after(:create) build a paid order with line items?
answer
- sequence(:number) { |n| ... }
- trait :paid, combined at the call site
- transient values never reach the model
- after(:create) receives order and evaluator
- explicit overrides beat traits
basics
~20 sA sequence gives each order a unique number, trait :paid adds the payment attributes, and a transient line_items_count read in after(:create) |order, evaluator| calls create_list for the items; create(:order, :paid, :with_line_items, line_items_count: 2) combines them.
solid answer
~40 sIn factory_bot I keep the base `:order` factory minimal: a `customer` association and `sequence(:number) { |n| "BM-#{n.to_s.rjust(5, "0")}" }`, so every order gets a unique number. Variations go in **traits**: `trait :paid do paid_at { 1.hour.ago } end`, applied by name, `create(:order, :paid)`. Traits combine, and a later trait wins over an earlier one. For children, a trait declares a **transient** attribute, `transient do line_items_count { 3 } end`, which callers can override but which is never assigned to the model. An `after(:create) do |order, evaluator| ... end` callback reads `evaluator.line_items_count` and calls `create_list(:line_item, evaluator.line_items_count, order: order)`. Overrides passed at the call site beat both the factory and its traits.
code
ruby · 23 linesFactoryBot.define do
factory :order do
customer
sequence(:number) { |n| "BM-#{n.to_s.rjust(5, "0")}" }
trait :paid do
paid_at { 1.hour.ago }
end
trait :with_line_items do
transient do
line_items_count { 3 }
end
after(:create) do |order, evaluator|
create_list(:line_item, evaluator.line_items_count, order: order)
order.line_items.reset
end
end
end
end
create(:order, :paid, :with_line_items, line_items_count: 2)go deeper
Know how to define a factory with a sequence and a trait, and how to call create(:order, :paid).
Explain trait precedence, transient attributes read through the evaluator, and why after(:create) does not run for build.
Keep base factories minimal, move expensive children into traits, and write callbacks that share the parent instead of cascading.
Agree team rules for trait naming and factory scope so factories document the domain rather than accumulating one-off cases.
## The pieces of a factory | Piece | Purpose | Example | |---|---|---| | attribute block | default value, evaluated per object | `notes { nil }` | | association | builds or creates a parent | `customer` | | `sequence` | unique value per call | `sequence(:number) { \|n\| "BM-#{n}" }` | | `trait` | named bundle of attributes and callbacks | `trait :paid do ... end` | | `transient` | input for the factory, not a model attribute | `line_items_count { 3 }` | | callback | code around a strategy step | `after(:create) { \|order, evaluator\| ... }` | Attribute values must be **blocks** (`notes { nil }`); the static form `notes nil` was removed in factory_bot 5. ## Sequences - `sequence(:number) { |n| "BM-#{n.to_s.rjust(5, "0")}" }` inside a factory gives each built object the next value, starting at 1. - A global sequence defined directly under `FactoryBot.define` is read with `generate(:email)`. - The counter lives in the Ruby process, not in the database. Rolled-back tests do not rewind it, so never assert on a specific number. `FactoryBot.rewind_sequences` resets the counters when you really need that. ## Traits ```ruby trait :paid do paid_at { 1.hour.ago } payment_reference { "pay_#{number}" } end ``` - Apply by name: `create(:order, :paid)`. Several traits combine: `create(:order, :paid, :gift_wrapped)`. - When two traits set the same attribute, the **last one listed wins**. - Explicit overrides win over everything: `create(:order, :paid, paid_at: 2.days.ago)`. - A child factory can bake traits in: `factory :paid_order, traits: [:paid]`. - For a model with an `enum`, factory_bot also defines one trait per enum value automatically (`automatically_define_enum_traits` is `true`). ## Transient attributes and callbacks ```ruby trait :with_line_items do transient do line_items_count { 3 } end after(:create) do |order, evaluator| create_list(:line_item, evaluator.line_items_count, order: order) order.line_items.reset end end ``` - `transient` values can be overridden at the call site (`line_items_count: 1`) but are **not** assigned to the `Order`. - A callback block that takes two arguments receives the object and the **evaluator**, which exposes transient and regular attributes. - Callback names: `after(:build)`, `before(:create)`, `after(:create)`, `after(:stub)`, plus `before(:build)` and `before(:all)` / `after(:all)` in recent 6.x releases. - `after(:create)` only runs for `create`. To make the trait work with `build` too, build the children inline instead: `line_items { Array.new(line_items_count) { association(:line_item, order: instance) } }`. ## Putting it together 1. `create(:order)`: one order, one customer, a unique number. 2. `create(:order, :paid)`: the same, with payment fields set. 3. `create(:order, :paid, :with_line_items, line_items_count: 2)`: a paid order with two line items, each pointing at that order. ## Habits that keep factories honest - The base factory holds only what validations require; everything optional lives in a trait. - Callbacks that create children belong in traits, not in the base factory, so plain `create(:order)` stays cheap. - Pass the parent into `create_list`, as above. Otherwise each line item's own `order` association creates a separate order. ## Child factories and inheritance A nested factory inherits everything from its parent and can add or override attributes: ```ruby factory :order do customer factory :gift_order do gift_message { "Happy birthday" } end end ``` - `create(:gift_order)` builds an `Order` with the base attributes plus the message. - Prefer traits for variations that combine, such as paid and gift-wrapped, and child factories for named shapes the domain really has. - `factory :paid_gift_order, parent: :gift_order, traits: [:paid]` composes both styles when a name reads better in tests. ## Sequences and parallel workers Rails' parallel test workers are forked processes. Each worker carries on from the sequence counter it inherited, so two workers can produce the same order number. That does not collide, because each worker writes to its own database. Collisions only appear when tests share something outside the database, such as an external sandbox that also requires unique numbers.
- Why is order.line_items reset inside the after(:create) callback in a factory_bot trait?If anything loaded `order.line_items` before the callback ran, the association has cached an empty collection. `create_list` writes rows through the line items' own `order` foreign key, not through that cached collection. Resetting the association, or calling `order.reload`, makes the next read query the database and see the new items.
- In factory_bot, what happens if you pass line_items_count: 2 without the :with_line_items trait?The transient attribute is declared inside the trait, so without the trait the factory does not know it. factory_bot then treats it as an ordinary override and tries to assign `line_items_count=` on the `Order`, which raises `NoMethodError` unless the model has such an attribute. Declare the transient in the base factory if callers should be able to pass it without the trait.
A base factory is the plain tour T-shirt, traits are the print options you tick on the order form, and a transient attribute is the quantity box: it shapes what gets made, but it is never printed on the shirt itself.
- Transient attributes are saved on the model like any other attribute.
- after(:create) callbacks also run when you call build.
- The first trait listed wins when two traits set the same attribute.
- Sequences restart at 1 after each test's transaction rolls back.
- Factory attributes can be written statically, as number "BM-1".