ex_machina v2.1.0 ExMachina behaviour View Source
Defines functions for generating data
In depth examples are in the README
Link to this section Summary
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
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@example.com" then "me-1@example.com", etc.
email: sequence(:email, &"me-#{&1}@foo.com")
}
end
Link to this section Callbacks
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 use
d.
Example
def user_factory do
%{name: "John Doe", admin: false}
end
# Returns %{name: "John Doe", admin: true}
build(:user, admin: true)
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)
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)