Skip to content

Instantly share code, notes, and snippets.

@mhanberg
Created April 29, 2022 18:04
Show Gist options
  • Save mhanberg/708d5a7869a8defec604b22cb5792e25 to your computer and use it in GitHub Desktop.
Save mhanberg/708d5a7869a8defec604b22cb5792e25 to your computer and use it in GitHub Desktop.
Factores with Ecto
# example from the ecto guides https://hexdocs.pm/ecto/test-factories.html
defmodule MyApp.Factory do
alias MyApp.Repo
# Factories
def build(:post) do
%MyApp.Post{title: "hello world"}
end
def build(:comment) do
%MyApp.Comment{body: "good post"}
end
def build(:post_with_comments) do
%MyApp.Post{
title: "hello with comments",
comments: [
build(:comment, body: "first"),
build(:comment, body: "second")
]
}
end
def build(:user) do
%MyApp.User{
email: "hello#{System.unique_integer()}",
username: "hello#{System.unique_integer()}"
}
end
# Convenience API
def build(factory_name, attributes) do
factory_name |> build() |> struct!(attributes)
end
def insert!(factory_name, attributes \\ []) do
factory_name |> build(attributes) |> Repo.insert!()
end
end
# example copied out of my personal workout tracking app
defmodule Bifrost.HealthFixtures do
alias Bifrost.Health
@exercise_valid_attrs %{"category" => "Push", "name" => "some name", "type" => "Weight"}
@routine_valid_attrs %{"name" => "some name"}
def exercise_fixture(attrs \\ %{}) do
{:ok, exercise} =
attrs
|> Enum.into(@exercise_valid_attrs)
|> Health.create_exercise()
exercise
end
def routine_fixture(attrs \\ %{}) do
{:ok, routine} =
attrs
|> Enum.into(@routine_valid_attrs)
|> Health.create_routine()
routine
end
def workout_fixture(attrs \\ %{}) do
{:ok, workout} = attrs |> Health.create_workout()
workout
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment