Skip to content

Instantly share code, notes, and snippets.

@Nicolab
Forked from atomkirk/factory.ex
Created March 2, 2022 17:50
Show Gist options
  • Save Nicolab/7bfe58c85ced16fe1a55828926907d26 to your computer and use it in GitHub Desktop.
Save Nicolab/7bfe58c85ced16fe1a55828926907d26 to your computer and use it in GitHub Desktop.
Generating Example Data in Elixir
defmodule App.Factory do
alias App.Repo
def create(module, overrides \\ %{})
def create(module, overrides) when is_list(overrides), do: create(module, Map.new(overrides))
def create(module, overrides) do
attributes = module.example() |> Map.merge(overrides)
struct(module)
|> changeset(attributes)
|> Repo.insert!()
end
def changeset(%App.User{} = struct, attributes) do
App.User.registration_changeset(struct, attributes)
end
def changeset(%{__struct__: module} = struct, attributes) do
module.changeset(struct, attributes)
end
end
defmodule App.User do
use App.Web, :model
alias App.Repo
schema "users" do
field(:name, :string)
timestamps()
belongs_to(:account, App.Account)
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name])
|> validate_required([:name])
end
def example do
%{
name: Faker.Person.name(),
address: Faker.Address.street_address()
}
end
end
import App.Factory
account = create(App.Account, name: "My Company")
user = create(App.User, account_id: account.id) # %App.User{name: "Steve Urkel", account_id: 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment