Skip to content

Eloquex Factories

David Ciulla edited this page Nov 7, 2026 · 1 revision

Eloquex: Factories

Eloquex factories provide a fluent, composable API for generating model instances in tests and seeders. They are powered by Laravex.Eloquex.Factory and live in database/factories/.

Introduction

A factory module declares a definition/0 callback that returns a map of default attributes. At test time you override only the fields that matter:

# database/factories/post_factory.ex
defmodule Database.Factories.PostFactory do
  use Laravex.Eloquex.Factory, model: App.Models.Post

  def definition do
    %{
      "title"     => Laravex.Support.Faker.sentence(4),
      "body"      => Laravex.Support.Faker.paragraph(2),
      "published" => false,
      "user_id"   => 1
    }
  end
end

Making vs. Creating

Function Behaviour
make/0 / make/1 Returns a model struct without touching the database
create/0 / create/1 Persists to the database via Model.create/1
# In-memory only
post = Database.Factories.PostFactory.make()
post = Database.Factories.PostFactory.make(%{"title" => "Custom"})

# Persisted
post = Database.Factories.PostFactory.create()
post = Database.Factories.PostFactory.create(%{"user_id" => user.id})

Attributes passed to make/1 and create/1 are deep-merged over definition/0, so you only need to specify what differs.

Creating Multiple Records

# Create 10 persisted posts
posts = Database.Factories.PostFactory.count(10)

# Create 5 posts with overrides
posts = Database.Factories.PostFactory.count(5, %{"published" => true})

# Make (not persist) 10 structs
posts = Database.Factories.PostFactory.make_many(10)

States

States are named attribute overrides that adjust the factory for a specific scenario. Declare them with defstate/2:

defmodule Database.Factories.PostFactory do
  use Laravex.Eloquex.Factory, model: App.Models.Post

  def definition do
    %{"title" => Laravex.Support.Faker.sentence(), "published" => false}
  end

  defstate :published do
    %{"published" => true, "published_at" => DateTime.utc_now() |> DateTime.to_iso8601()}
  end

  defstate :draft do
    %{"published" => false}
  end
end

Apply a state via create_state/2 or make_state/2:

# Create a published post
post = Database.Factories.PostFactory.create_state(:published)

# Create a published post with extra overrides
post = Database.Factories.PostFactory.create_state(:published, %{"title" => "Breaking News"})

# Make without persisting
post = Database.Factories.PostFactory.make_state(:draft)

Sequences

sequence/0 returns an ever-increasing integer per factory, useful for generating unique values:

def definition do
  n = sequence()
  %{
    "email" => "user#{n}@example.test",
    "name"  => "User #{n}"
  }
end

Sequences are stored in ETS under {FactoryModule, "default"} and persist within the test run. Each call to sequence() atomically increments the counter.

Named sequences:

sequence("orders")   # separate counter for "orders"

The Default UserFactory

Laravex ships a Database.Factories.UserFactory that you can use directly in tests and seeders:

# Create a standard verified user
user = Database.Factories.UserFactory.create()

# Create an unverified user
user = Database.Factories.UserFactory.create_state(:unverified)
# OR
user = Database.Factories.UserFactory.unverified()

The :unverified state sets email_verified_at to nil.

Fake Data Helpers

Factory definitions commonly use Laravex.Support.Faker:

Laravex.Support.Faker.name()          # => "Beau Chen"
Laravex.Support.Faker.email()         # => "beau.chen9273@example.test"
Laravex.Support.Faker.sentence()      # => "Alpha brave calm delta eager."
Laravex.Support.Faker.paragraph()     # => multi-sentence string
Laravex.Support.Faker.boolean()       # => true | false
Laravex.Support.Faker.number(1, 100)  # => integer
Laravex.Support.Faker.uuid()          # => UUID v4 string

See Seeding for Faker reference and seeder conventions.

Using Factories in Tests

defmodule Tests.Feature.PostTest do
  use Laravex.TestCase, async: false

  test "shows a post" do
    user = Database.Factories.UserFactory.create()
    post = Database.Factories.PostFactory.create(%{
      "user_id"   => user.id,
      "title"     => "Hello World",
      "published" => true
    })

    response = get("/posts/#{post.id}")
    assert_status(response, 200)
    assert_see(response, "Hello World")
  end
end

See Also

  • Seeding — DatabaseSeeder and db:seed
  • Eloquex — Model creation and persistence
  • Testing — TestCase and test layout

Clone this wiki locally