View Source Factoid behaviour (factoid v0.1.2)

Documentation for Factoid.

Factoid is a library for generating test data using factories build on Ecto.Schemas.

It's similar to ExMachina but it is not a drop-in replacement. Where ExMachina builds and keeps associations in the returned records, Factoid drops the associations and keeps the associated id fields. This opinionated approach helps building simpler tests.

installation

Installation

Add factoid to the list of dependencies in mix.exs:

def deps do
  [{:factoid, "~> 0.1"}]
end

usage

Usage

Define a factory module that uses the Factoid behaviour, select the repo module, and define build/2 functions for each factory.

def App.Factory do
  @behaviour Factoid

  use Factoid, repo: App.Repo

  alias App.Schemas.User
  alias App.Schemas.UserAvatar

  @impl Factoid
  def build(factory, attrs \\ %{})

  def build(:user, attrs) do
    %User{
      first_name: "Jane",
      last_name: "Doe",
      email_address: "jane-#{unique_integer()}@example.com",
    }
    |> Map.merge(attrs)
  end

  def build(:user_avatar, attrs) do
    %UserAvatar{
      user: build(:user)
    }
    |> Map.merge(attrs)
  end
end

In your tests you can import your factory and use it to create test data.

def App.ModuleTest do
  use DataCase

  import App.Factory

  alias App.Repo
  alias App.Schemas.User

  test "creates a user" do
    user_1 = insert(:user)
    user_2 = insert(:user, name: "John")

    assert user_1 != user_2
    assert user_1 == Repo.get(User, user_1.id)
    assert user_2.name == "John"
  end
end

Link to this section Summary

Callbacks

Builds a record.

Builds a record with attributes.

Functions

Inserts a record with attributes.

Generates a systemically unique integer.

Generates a UUID.

Link to this section Callbacks

@callback build(factory_name()) :: term()

Builds a record.

Link to this callback

build(factory_name, attrs)

View Source
@callback build(factory_name(), attrs()) :: term()

Builds a record with attributes.

Link to this section Functions

Link to this function

insert(repo, factory_name, build, attrs \\ %{})

View Source
@spec insert(module(), factory_name(), (... -> any()), attrs()) :: record()

Inserts a record with attributes.

@spec unique_integer() :: non_neg_integer()

Generates a systemically unique integer.

@spec unique_uuid() :: Ecto.UUID.t()

Generates a UUID.