ex_machina v2.0.0 ExMachina.Ecto

Module for building and inserting factories with Ecto

This module works much like the regular ExMachina module, but adds a few nice things that make working with Ecto easier.

  • It uses ExMachina.EctoStrategy, which adds insert/1, insert/2, insert_pair/2, insert_list/3.
  • Adds a params_for function that is useful for working with changesets or sending params to API endpoints.

More in-depth examples are in the README.

Summary

Functions

Builds a factory with the passed in factory_name and returns its fields

Same as params_for/2, but inserts all belongs_to associations and sets the foreign keys

Similar to params_for/2 but converts atom keys to strings in returned map

Similar to params_with_assocs/2 but converts atom keys to strings in returned map

Functions

params_for(module, factory_name, attrs \\ %{})

Builds a factory with the passed in factory_name and returns its fields

This is only for use with Ecto models.

Will return a map with the fields and virtual fields, but without the Ecto metadata, the primary key, or any belongs_to associations. This will recursively act on has_one associations and Ecto structs found in has_many associations.

If you want belongs_to associations to be inserted, use params_with_assocs/2.

If you want params with string keys use string_params_for/3.

Example

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

# Returns %{name: "John Doe", admin: true}
params_for(:user, admin: true)
params_with_assocs(module, factory_name, attrs \\ %{})

Same as params_for/2, but inserts all belongs_to associations and sets the foreign keys.

If you want params with string keys use string_params_with_assocs/3.

Example

def article_factory do
  %MyApp.Article{title: "An Awesome Article", author: build(:author)}
end

# Inserts an author and returns %{title: "An Awesome Article", author_id: 12}
params_with_assocs(:article)
string_params_for(module, factory_name, attrs \\ %{})

Similar to params_for/2 but converts atom keys to strings in returned map.

The result of this function can be safely used in controller tests for Phoenix web applications.

Example

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

# Returns %{"name" => "John Doe", "admin" => true}
string_params_for(:user, admin: true)
string_params_with_assocs(module, factory_name, attrs \\ %{})

Similar to params_with_assocs/2 but converts atom keys to strings in returned map.

The result of this function can be safely used in controller tests for Phoenix web applications.

Example

def article_factory do
  %MyApp.Article{title: "An Awesome Article", author: build(:author)}
end

# Inserts an author and returns %{"title" => "An Awesome Article", "author_id" => 12}
string_params_with_assocs(:article)