Last active
March 2, 2022 17:50
-
-
Save atomkirk/e06ef4edba07cefdab0fc853dbb931db to your computer and use it in GitHub Desktop.
Generating Example Data in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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