Database: Model Factories
- Introduction
- Defining factories
- Creating models with factories
- Factory relationships
- After creating callbacks
- Inserting many rows
- Fake data
- Common pitfalls
- Testing with factories
Introduction
When testing your application or seeding your database, you often need realistic records to work with, such as a user and post for an authorization test or fifty users for a local demo. Spelling out every required column in every test adds boilerplate and makes adding a new required column break unrelated tests.
Model factories define sensible defaults for each model so your tests and seeders only specify the columns they care about:
let user = User::factory().create().await?;let posts = Post::factory() .count(3) .for_(Post::user, &user) .create() .await?;New applications include a factory for the User model right below the model definition:
// src/models/user.rsuse dust::auth::{Authenticatable, RememberToken};use dust::hash::PasswordHash;use dust::model::{Faker, IntoCreate, create, factory, model};use dust::time::Timestamp;#[model]#[derive(Authenticatable)]pub struct User { pub id: i64, pub name: String, pub email: String, pub email_verified_at: Option<Timestamp>, #[serde(skip)] pub password: PasswordHash, #[serde(skip)] pub remember_token: Option<RememberToken>, pub created_at: Timestamp, pub updated_at: Timestamp,}#[factory(User)]pub struct UserFactory;impl UserFactory { fn definition(fake: &mut Faker) -> impl IntoCreate<User> { create!(User { name: fake.name(), email: fake.unique().email(), email_verified_at: dust::now(), password: "password", }) } pub fn unverified(self) -> Self { self.state(|user, _| user.email_verified_at(None::<Timestamp>)) }}A factory is a unit struct annotated with #[factory(User)], which generates User::factory() on the model. Its definition method receives a Faker instance for generating fake data and returns the default attributes as a create! expression. Additional methods on the factory define reusable states.
Because User::factory().create() produces the same create builder as create!(User { .. }), model hooks, events, and nested creates all run automatically. Each create() call executes inside a single transaction, so parent and child records commit or roll back together.
Defining factories
Where factories live
Define each model's factory directly below its model struct (as User does) and re-export it from src/models/mod.rs:
// src/models/mod.rsmod post;mod user;pub use post::{Post, PostFactory};pub use user::{User, UserFactory};Keeping the factory next to the model means that when you add a new required column, the compiler error pointing to the factory is right in the same file.
Callers using User::factory() only need to import User; exporting UserFactory allows helper functions and seeders to reference the factory type directly.
Parents in a definition
Like any create! call, a factory definition must provide every required column without a database default, ensuring your factories stay in sync with your schema at compile time. For a #[belongs_to] relationship, you may assign another factory so each created post automatically gets its own author:
// src/models/post.rsuse dust::model::{Faker, IntoCreate, create, factory};use crate::models::User;#[factory(Post)]pub struct PostFactory;impl PostFactory { fn definition(fake: &mut Faker) -> impl IntoCreate<Post> { create!(Post { user: User::factory(), title: fake.sentence(), body: fake.paragraph(), }) }}The parent user is inserted alongside the post in the same transaction. Whenever a caller supplies an existing user through an override, for_, or has, dust-framework skips the definition's User::factory() completely.
#[morph_to] relationships also accept a factory, so a comment's definition may set commentable: Post::factory() while an override like create!(Comment::factory() { commentable: &video }) attaches the comment to a video instead.
Factory states
Factory states let you define reusable modifications to a model's default attributes, such as a published post or a suspended user. Write each state as a method returning Self that calls self.state(...), passing a closure that receives the create builder and Faker:
// src/models/post.rsuse dust::time::ToSpan;impl PostFactory { pub fn published(self) -> Self { self.state(|post, _| post.published_at(dust::now())) } pub fn scheduled(self) -> Self { self.state(|post, fake| post.published_at(fake.future(1.week()))) }}States run after definition in the order you chain them, with later states overriding earlier values for the same column. Because the closure executes once per created row, capture any state parameter by value and pass it to the column setter by reference:
impl PostFactory { pub fn titled(self, title: impl Into<String>) -> Self { let title = title.into(); self.state(move |post, _| post.title(&title)) }}For a one-off tweak inside a test, call state inline:
let post = Post::factory() .state(|post, _| post.title("Draft")) .create() .await?;Factory cheat sheet
| Call | What it does |
|---|---|
Model::factory() |
Starts a builder with the definition's defaults |
.state(closure) |
Changes attributes for every created row |
.sequence(closure) |
Changes attributes by row index |
.count(n) |
Creates n rows and returns a Vec |
.has(Relationship, factory) |
Creates or attaches related models through a relationship |
.for_(Relationship, parent) |
Points a #[belongs_to] or #[morph_to] at one shared parent |
.recycle(&model) |
Reuses a model wherever the tree would create that type |
.after_creating(callback) |
Runs extra async work inside the transaction |
.create() |
Inserts and returns hydrated models |
.insert() |
Bulk-inserts without hydrating models |
.quietly() |
Skips model events for the created rows |
Creating models with factories
Call create() and await it to insert a model and return it, or chain count(n) before create() to insert multiple records and return a Vec:
use app::models::User;let user = User::factory().create().await?;let users = User::factory() .unverified() .count(3) .create() .await?;Always call custom factory state methods before count. Calling count transitions the builder into Many<User>, which supports state, sequence, and relationship helpers, but not custom methods defined on UserFactory (so User::factory().count(3).unverified() will not compile).
Model hooks and Created events fire for every created record. To suppress events when creating models, chain quietly():
let users = User::factory().count(50).create().quietly().await?;[!NOTE] When running factories inside a database seeder, you can mute model events for the entire seeder using
#[seeder(without_events)]instead of chainingquietly()on each call.
Overriding columns
To override specific attributes when creating a record, pass the factory to create!. Column names and value types are still checked at compile time:
use dust::model::create;let taylor = create!(User::factory() { name: "Taylor", email: "taylor@example.com",}).await?;You may also chain column setters directly after create(), which pairs naturally with factory states:
let abigail = User::factory() .unverified() .create() .name("Abigail") .await?;You can combine attribute overrides with has to create related models at the same time:
let user = create!(User::factory() { name: "Taylor" }) .has(User::posts, Post::factory().count(3)) .await?;To create multiple records with distinct overrides, pass a list to create!:
let users = create!([ User::factory() { name: "Taylor" }, User::factory() { name: "Abigail" },]).await?;Sequences
Use sequence when an attribute should vary from one generated record to the next. The closure receives the create builder, Faker, and the zero-based row index. For example, this creates ten users with every second user verified:
let users = User::factory() .count(10) .sequence(|user, _, index| { user.email_verified_at((index % 2 == 0).then(dust::now)) }) .create() .await?;Creating or inserting
create() returns the rows it wrote, which is what tests usually want. insert() writes the same rows without hydrating them, which is what a large seeder wants. The difference is not only speed:
| Need | create() |
insert() |
|---|---|---|
| The created models back | Yes | No |
| Hooks and model events | Yes | No |
after_creating callbacks |
Yes | No |
| Nested parents from a definition | Yes | No, supply them with for_ or recycle |
| Timestamps and hashed passwords | Yes | Yes |
| Thousands of rows | One insert per model | Batched multi-row inserts |
insert() fails before executing its statement when a row still needs a parent that it cannot create, so a definition with user: User::factory() needs .for_(Post::user, &user) or .recycle(&user) before you insert. It also skips after_creating, so a state that attaches a role must run with create().
Factory relationships
Has one and has many
Use has to create related child models for each parent record through a #[has_one] or #[has_many] relationship:
let user = User::factory() .has(User::posts, Post::factory().published().count(3)) .create() .await?;assert_eq!(user.posts.len(), 3);dust-framework sets each child's foreign key to the new parent's ID and hydrates the relationship on the returned models automatically, so user.posts holds the three posts and each post's user holds the new user without extra queries. Children created through #[morph_one] or #[morph_many] also populate their #[morph_to] field automatically. You may nest has calls and combine them with count to build multi-level trees:
let users = User::factory() .count(5) .has( User::posts, Post::factory() .count(3) .has(Post::comments, Comment::factory().count(2)), ) .create() .await?;This creates 5 users, 15 posts, and 30 comments in one transaction. Passing a factory for the wrong model type, such as has(User::posts, Comment::factory()), fails to compile.
Because a #[has_one] relationship holds a single record (such as profile: HasOne<Option<Profile>>), pass a single factory without count:
let user = User::factory() .has(User::profile, Profile::factory()) .create() .await?;Belongs to
Use for_ to associate created models with a shared parent through a #[belongs_to] relationship. It accepts either an existing model or another factory:
let user = User::factory().create().await?;let posts = Post::factory() .count(3) .for_(Post::user, &user) .create() .await?;let posts = Post::factory() .count(3) .for_(Post::user, User::factory().unverified()) .create() .await?;The first call associates all three posts with user. The second creates a single unverified user and assigns all three posts to that user. In both cases, the definition's default user: User::factory() is skipped so no extra users are created.
for_ also supports #[morph_to] relationships with any target model or factory listed in the polymorphic enum:
let comments = Comment::factory() .count(3) .for_(Comment::commentable, &video) .create() .await?;let comments = Comment::factory() .count(3) .for_(Comment::commentable, Post::factory()) .create() .await?;The first argument must be a #[belongs_to] or #[morph_to] relationship descriptor on the model (such as Post::user), and passing a create! expression instead of a model or factory fails to compile. If a model has multiple relationships to the same target type, such as a category's parent and children, passing the wrong direction (Category::children) panics with a message pointing to the fix.
Belongs to many
When called on a #[belongs_to_many] relationship, has either creates new related models and attaches them via the join table, or attaches existing models:
let post = Post::factory() .has(Post::tags, Tag::factory().count(3)) .create() .await?;let tags = Tag::factory().count(3).create().await?;let posts = Post::factory() .count(5) .has(Post::tags, &tags) .create() .await?;The second call attaches the same three tags to every one of the five posts, with post.tags populated on each returned post. Just like attach, has accepts a single model, an array, a Vec, or a slice by value or by reference. To populate extra columns on the join table, pass a tuple containing the related models and db::values!:
use dust::db;let post = Post::factory() .has(Post::tags, (Tag::factory().count(2), db::values! { pinned: true })) .create() .await?;If the join columns depend on each attached model's position, pass a closure receiving the zero-based index instead:
let post = Post::factory() .has( Post::tags, (&tags, |index: usize| db::values! { pinned: index == 0 }), ) .create() .await?;For relationships declared with a typed join row such as BelongsToMany<Role, Membership>, pass the join attributes using joined!:
use dust::model::joined;let user = User::factory() .has( User::roles, (Role::factory(), joined!(Membership { level: "owner" })), ) .create() .await?;Because the factory does not re-query typed join rows after inserting them, call load(User::roles) before reading join row fields.
has also works across #[morph_to_many] and #[morphed_by_many] relationships and populates the type column on each join row. Relationships declared with a join row, such as MorphToMany<Tag, Tagging>, do not hydrate the created tags automatically, so call load(Post::tags) before reading them.
Recycling models
When a comment references both a post and a user, and the post also references a user, Comment::factory().create() would normally create two separate users. recycle reuses an existing model across every factory in the create tree, including nested parents and children, wherever that model type would otherwise be created:
let user = User::factory().create().await?;let comments = Comment::factory() .count(3) .recycle(&user) .create() .await?;Every comment and every post is now associated with user. recycle also reaches factories passed to for_, so Comment::factory().for_(Comment::post, Post::factory()).recycle(&user) creates one post for user. You may also pass a slice such as &users to pick one model at random for each parent.
You may also call recycle on a create! override:
let comment = create!(Comment::factory() { body: "Thanks!" }) .recycle(&user) .await?;After creating callbacks
When creating a row requires extra work beyond its columns or direct relationships, use after_creating to run an async closure with each created model inside the factory's transaction. For example, the admin state below finds or creates a shared "admin" role and attaches it to every user created with User::factory().admin():
// src/models/user.rsuse crate::models::Role;impl UserFactory { pub fn admin(self) -> Self { self.after_creating(|user| async move { let role = Role::first_or_create( Role::name.eq("admin"), create!(Role { name: "admin" }), ) .await?; user.roles().attach(&role).await?; Ok(()) }) }}The closure receives each model with any factory-created relationships already loaded. If the callback returns an error, the entire transaction rolls back and the error is returned to the caller.
Inserting many rows
When seeding thousands of rows that you do not need returned as hydrated models, call insert() instead of create(). It writes rows using batched multi-row INSERT statements and returns ():
let users = User::factory().count(10).create().await?;let posts = Post::factory().count(50).recycle(&users).create().await?;Comment::factory() .count(10_000) .recycle(&users) .recycle(&posts) .insert() .await?;insert sets timestamps automatically, but skips model hooks, events, and after_creating callbacks. Because it cannot create nested parent rows, supply existing parents via recycle, for_, or explicit foreign keys in a state; otherwise the call returns an error before executing.
Fake data
Factory definitions, states, and sequences receive a Faker instance that generates realistic random values on every run:
| Method | Returns |
|---|---|
name(), first_name(), last_name(), user_name() |
A person's name, or part of one |
email() |
An address at example.com, example.org, or example.net, which can't receive mail |
word(), words(5), slug(), sentence(), paragraph(), paragraphs(3) |
Lorem ipsum text and hyphenated slugs |
number(1..=100), decimal(1..=999, 2), float(0.0..=5.0) |
An integer, Decimal, or f64 in the range |
boolean(25) |
true 25% of the time |
pick(&["draft", "review", "live"]) |
One of the items |
past(30.days()), future(1.week()), between(start, end) |
A Timestamp before, after, or between times |
past_date(30.days()), future_date(1.year()), date_between(start, end) |
A Date before, after, or between calendar dates |
company(), street_address(), city(), state(), postal_code(), country(), country_code(), phone_number() |
Address book data |
url(), ipv4(), ipv6() |
Web and network addresses reserved for examples and documentation |
uuid(), ulid(), alphanumeric(10) |
Identifiers |
Unique values
For columns with a unique index, such as email, chain unique() on Faker so generated values do not repeat within the running application:
create!(User { name: fake.name(), email: fake.unique().email(), password: "password",})When a generated value repeats several times in a row, unique() appends a number, such as ayla.hirthe.2@example.net, so it never runs out. unique().number(..) and unique().alphanumeric(..) cannot append a suffix and panic once their range is nearly exhausted. Note that unique() only tracks values generated in memory, not existing rows already in the database table.
Passwords
When a factory assigns a plain-text string to a PasswordHash column (such as password: "password"), dust-framework caches the bcrypt hash per application so creating 1,000 test users computes only one hash instead of 1,000. Calls to create! outside a factory always compute a fresh hash.
Repeatable values
When a test fails on a fake value, you want the next run to fail on that value again. Tests marked with #[dust::test] seed the application's faker from the test's name, so a test gets the same fake values each time it runs.
If you'd like repeatable values outside a test, such as in a seeder that builds a demo database, call Faker::seed with a seed of your own:
use dust::model::Faker;Faker::seed(42);Common pitfalls
- Put custom state methods before
count.countchanges the builder toMany<Model>, which no longer has your factory's own methods, soUser::factory().count(3).unverified()does not compile. CallUser::factory().unverified().count(3). unique()only remembers what it generated. It does not inspect existing rows, so a seeder that runs twice can still collide with an address from the first run. Use fixed values for reference data, or an upsert.unique().number(..)can run out. Unlike names and emails, a number cannot gain a suffix, so a small range withunique()panics once it is nearly exhausted. Usesequenceinstead when you need guaranteed distinct numbers.for_takes a parent relationship, not a child one. PassingCategory::childrenwhere the model expectsCategory::parentpanics with a message naming the direction; the relationship must be#[belongs_to]or#[morph_to].- Typed join rows are not hydrated after a factory write. When a relationship uses
BelongsToMany<Role, Membership>, callload(User::roles)before readingrole.join. insert()skips the lifecycle. Hooks, events,after_creating, and nested parent creation all requirecreate().- Recycling a slice picks at random. With
recycle(&users), every parent that would be created takes one user from the slice, chosen randomly per row; the result is not round-robin. - Factories are checked like
create!. A new required column breaks the definition at compile time, which is the point: fix the factory once instead of every test.
Testing with factories
In tests, use factories to set up your database state, send requests, and verify the result with assert_model_exists, assert_model_missing, and the other database assertions:
// tests/posts.rsuse dust::testing::prelude::*;use app::models::{Post, User};#[dust::test]async fn users_can_delete_their_posts(app: Application) -> dust::Result<()> { let user = User::factory().create().await?; let post = Post::factory().for_(Post::user, &user).create().await?; app.delete(&format!("/posts/{}", post.id)) .acting_as(&user) .await .assert_redirect(); app.assert_model_missing(&post).await; Ok(())}Because fake values vary on every test run, assert against values your test set explicitly or read them from the returned factory models (such as user.email).