With factory_bot, how do build, create, build_stubbed and attributes_for differ, and which of them write to the database?
answer
- only create calls save!
- build builds its associations too
- build_stubbed fakes an id from 1001
- attributes_for drops associations
- create_list and build_pair
basics
~20 sOnly create writes: it builds the object and calls save!. build returns an unsaved instance, build_stubbed an unsaved one that pretends to be persisted with a fake id, and attributes_for a plain hash without associations.
solid answer
~40 sWith factory_bot, `build(:order)` instantiates the model and assigns attributes without saving. Because `FactoryBot.use_parent_strategy` defaults to `true`, its associations are built too. `create(:order)` does the same and then calls `save!`, so validations and model callbacks run, an invalid factory raises `ActiveRecord::RecordInvalid`, and associations are created first. `build_stubbed(:order)` never touches the database. It assigns a fake id (counting up from 1001), makes `persisted?` return true, fills timestamps, stubs its associations as well, and raises if you call `save`, `update` or `reload`. `attributes_for(:order)` returns a hash of attribute values with declared associations left out, which suits request params. Each strategy has `_list` and `_pair` forms, such as `create_list(:order, 3)`.
code
ruby · 11 linesorder = build(:order)
order.new_record? # => true
order.customer.new_record? # => true (use_parent_strategy)
stubbed = build_stubbed(:order)
stubbed.id # => 1001
stubbed.persisted? # => true
stubbed.save # raises RuntimeError
attributes_for(:order) # => { number: "BM-00007", notes: nil }
create_list(:line_item, 3, order: create(:order))go deeper
Know that create saves with save!, build does not, build_stubbed fakes persistence, and attributes_for returns a hash for params.
Explain use_parent_strategy, why create raises RecordInvalid for a bad factory, and what build_stubbed overrides and refuses.
Choose the cheapest strategy per test, and spot when a build still writes because of association strategy settings.
Set suite-wide strategy conventions, such as stubbed by default for presenters, so test speed holds as factories grow.
## Four strategies, one factory A **factory** in factory_bot describes how to make one kind of object. The **strategy** you call decides what happens to the result: | Call | Returns | Database writes | Associations | |---|---|---|---| | `build(:order)` | unsaved `Order` | none | built with the same strategy | | `create(:order)` | saved `Order` | `INSERT` via `save!` | created first | | `build_stubbed(:order)` | unsaved `Order` that claims to be persisted | none | stubbed | | `attributes_for(:order)` | `Hash` of attributes | none | left out of the hash | Each one also has a list and a pair form: `create_list(:line_item, 3, order: order)`, `build_pair(:order)`, `build_stubbed_list(:order, 5)`. ## build - Calls the model's constructor, assigns the attributes and runs `after(:build)` callbacks. - Nothing is saved, so model validations have not run, and `new_record?` is true. - Since factory_bot 5, **`FactoryBot.use_parent_strategy` is `true`**: an association declared in the factory follows the parent's strategy. `build(:line_item)` therefore builds, not creates, its `order` and `product`. A per-association `strategy: :create` overrides this. ## create - Does everything `build` does, then runs `before(:create)`, persists the object with the factory's `to_create`, which defaults to `save!`, then runs `after(:create)`. - Because it is `save!`, the model's validations and Active Record callbacks run, and an invalid factory raises `ActiveRecord::RecordInvalid` at the call site. - Associations are created first, so `create(:line_item)` can insert an order, a customer, a product and a band. ## build_stubbed - Never opens a connection for the object itself. It assigns an id from a counter (1001, 1002 and so on, or a UUID for UUID keys), sets `created_at` and `updated_at`, and clears change tracking. - Overrides `persisted?` to return `true`, `new_record?` to return `false`, and `destroyed?` to return `false`, so `order_path(order)` and `form_with(model: order)` behave as for a saved record. - Replaces `save`, `save!`, `update`, `destroy`, `reload`, `touch`, `update_column` and similar methods with ones that raise a `RuntimeError` ("stubbed models are not allowed to access the database"). - Associations declared in the factory are stubbed too, whatever `use_parent_strategy` says. - It is the fastest choice for presenters, helpers, policies and anything that only reads attributes. ## attributes_for - Returns a hash such as `{ number: "BM-00042", notes: nil }`. - Declared associations and transient attributes are left out, so `post orders_url, params: { order: attributes_for(:order) }` sends no `customer_id`. Merge it yourself: `attributes_for(:order).merge(customer_id: customer.id)`. - Inline associations written as `customer { association :customer }` appear in the hash as `nil`. ## Picking one 1. Need the row in the database, because a query, a uniqueness check or a request reads it? Use `create`. 2. Need a model object, and nothing reads it back from the database? Use `build`, or `build_stubbed` when the code also asks `persisted?` or needs an id. 3. Need form params? Use `attributes_for`, plus the foreign keys. Defaulting to `create` everywhere is the most common cause of slow suites, because every call writes the whole association graph. ## Customising what create does The persistence step is configurable per factory, which matters for objects that are not plain Active Record rows: - `to_create { |instance| instance.save!(validate: false) }` replaces the default `save!`. Use it sparingly, because it lets invalid records into the database just as fixtures do. - `skip_create` makes `create` behave like `build` for objects that have nowhere to be saved, such as a plain Ruby value object. - `initialize_with { new(order, currency: "EUR") }` changes how the object is constructed, for classes whose constructor takes arguments. - `FactoryBot.build_stubbed_starting_id = 5000` moves the stubbed id counter, which helps when fake ids would collide with ids that a test also creates for real. ## A quick way to remember them | Question the test asks | Strategy | |---|---| | "Is this row in the database?" | `create` | | "Does this object compute the right thing?" | `build` | | "Does this view or presenter treat it as saved?" | `build_stubbed` | | "What would the form post?" | `attributes_for` |
- Why might build(:line_item) still insert rows in an older factory_bot suite?Before factory_bot 5, associations defaulted to `create` even when the parent was built, and some suites keep that by setting `FactoryBot.use_parent_strategy = false`. A factory can also force it per association with `association :order, strategy: :create`. Either way `build` writes the parents, so check the setting and the factory before assuming `build` is free.
- When does build_stubbed break a test that build would pass?When the code under test persists or reloads the object, for example calling `update` or `reload`. The stubbed methods raise a `RuntimeError`. Reading a `has_many` collection on a stubbed record also misses, because the fake id matches no rows. Use `build_stubbed` for code that only reads the object's own attributes and its stubbed `belongs_to` targets.
- build saves the record but skips validations.
- create inserts rows with SQL and skips the model's callbacks.
- build_stubbed objects return false from persisted? and have a nil id.
- attributes_for includes the customer_id of the associated record.
- build(:line_item) always creates its order in the database.
Assumes factory_bot 6.6 through factory_bot_rails 6.5 on Rails 8.1; use_parent_strategy has defaulted to true since factory_bot 5.0.