model-mysql or model-postgres or model-sqlite only.Expand description
Factories for models: #[derive(Factory)] (next to #[derive(Model)])
gives a model T::factory(), a ModelFactory that builds instances
with a default value for every field, overrides from
with, and saves them with
create.
use rust_web_server::{Factory, Model};
#[derive(Model, Factory, Debug, Clone)]
#[table(name = "users")]
pub struct User {
#[primary_key(auto_increment)]
pub id: i64,
pub name: String, // "name-1", "name-2", …
pub email: String, // "email-1@example.com", …
pub age: Option<i32>, // None
pub admin: bool, // false
}
let ann = User::factory().with(|u| u.name = "Ann".into()).create(&pool).await?;
assert!(ann.id > 0);
let unsaved = User::factory().build();
let five = User::factory().create_many(5, &pool).await?;Default values (FactoryValue): numbers 0, bool false, Option
None, a String the field’s name and a sequence number (name-3; for
a field whose name contains email, email-3@example.com), so unique
columns stay unique. The primary key is 0 when it’s
auto_increment (the database picks it) and the sequence number
otherwise; #[ignore] fields and field types without a FactoryValue
get Default::default().
The sequence is per model type and process-wide — counting across the
tests that run in the process, in whatever order they run — so assert on
the values a factory returns, not on name-1.
Structs§
- Model
Factory - Builds instances of
T; fromT::factory().
Traits§
- Factory
- A model a factory can build; implemented by
#[derive(Factory)]. - Factory
Value - A type with a factory default; see the module docs for the values.