ex_machina v2.2.2 ExMachina behaviour View Source

Defines functions for generating data

In depth examples are in the README

Link to this section Summary

Functions

Shortcut for creating unique string values

Create sequences for generating unique values

Callbacks

Builds a single factory

Builds two factories

Link to this section Functions

Shortcut for creating unique string values.

This is automatically imported into a model factory when you use ExMachina.

This is equivalent to sequence(name, &"#{name}#{&1}"). If you need to customize the returned string, see sequence/2.

Note that sequences keep growing and are not reset by ExMachina. Most of the time you won’t need to reset the sequence, but when you do need to reset them, you can use ExMachina.Sequence.reset/0.

Examples

def user_factory do
  %User{
    # Will generate "username0" then "username1", etc.
    username: sequence("username")
  }
end

def article_factory do
  %Article{
    # Will generate "Article Title0" then "Article Title1", etc.
    title: sequence("Article Title")
  }
end
Link to this function sequence(name, formatter) View Source
sequence(any(), (integer() -> any()) | [...]) :: any()

Create sequences for generating unique values.

This is automatically imported into a model factory when you use ExMachina.

The name can be any term, although it is typically an atom describing the sequence. Each time a sequence is called with the same name, its number is incremented by one.

The formatter function takes the sequence number, and returns a sequential representation of that number – typically a formatted string.

Examples

def user_factory do
  %{
    # Will generate "me-0@foo.com" then "me-1@foo.com", etc.
    email: sequence(:email, &"me-#{&1}@foo.com"),
    # Will generate "admin" then "user", "other", "admin" etc.
    role: sequence(:role, ["admin", "user", "other"])
  }
end

Link to this section Callbacks

Link to this callback build(factory_name, attrs) View Source
build(factory_name :: atom(), attrs :: keyword() | map()) :: any()

Builds a single factory.

This will defer to the [factory_name]_factory/0 callback defined in the factory module in which it is used.

Example

def user_factory do
  %{name: "John Doe", admin: false}
end

# Returns %{name: "John Doe", admin: true}
build(:user, admin: true)
Link to this callback build_list(number_of_records, factory_name, attrs) View Source
build_list(
  number_of_records :: integer(),
  factory_name :: atom(),
  attrs :: keyword() | map()
) :: list()

Builds any number of factories.

Example

# Returns a list of 3 users
build_list(3, :user)
Link to this callback build_pair(factory_name, attrs) View Source
build_pair(factory_name :: atom(), attrs :: keyword() | map()) :: list()

Builds two factories.

This is just an alias for build_list(2, factory_name, attrs).

Example

# Returns a list of 2 users
build_pair(:user)