Skip to content

Instantly share code, notes, and snippets.

@atomkirk
Last active March 2, 2022 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atomkirk/e06ef4edba07cefdab0fc853dbb931db to your computer and use it in GitHub Desktop.
Save atomkirk/e06ef4edba07cefdab0fc853dbb931db 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