Define factories with ExMachina
mainYou can define factories using ExMachina (for plain structs/maps) or ExMachina.Ecto (for Ecto schemas).
Key Features in Factories:
- Sequences: Use
sequence/2to generate unique values (e.g., emails or titles). - Derived Attributes: Define attributes based on other values. You can use a direct value or an anonymous function for lazy evaluation.
- Associations: Use
build(:factory_name)to define associations. If usingExMachina.Ecto, these associations are automatically inserted when you callinsert. - Derived Factories: Create specialized versions of existing factories using
struct!/2.
defmodule MyApp.Factory do
# with Ecto
use ExMachina.Ecto, repo: MyApp.Repo
# without Ecto
use ExMachina
def user_factory do
%MyApp.User{
name: "Jane Smith",
email: sequence(:email, &"email-#{&1}@example.com"),
role: sequence(:role, ["admin", "user", "other"]),
}
end
def article_factory do
title = sequence(:title, &"Use ExMachina! (Part #{&1})")
slug = MyApp.Article.title_to_slug(title)
%MyApp.Article{
title: title,
slug: slug,
# lazy attribute via function
tags: fn article ->
if String.contains?(article.title, "Silly") do
["silly"]
else
[]
end
end,
# associations are inserted when you call `insert`
author: build(:user)
}
end
def featured_article_factory do
struct!(
article_factory(),
%{
featured: true,
}
)
end
end