Skip to content

Instantly share code, notes, and snippets.

@aptinio
Created February 9, 2018 09:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aptinio/955e22432f654fb3a21f53ab891a237b to your computer and use it in GitHub Desktop.
Save aptinio/955e22432f654fb3a21f53ab891a237b to your computer and use it in GitHub Desktop.
Roll your own factory for Ecto
defmodule Foo.Factory do
alias Foo.Blog.{Post, Comment}
def params_for(Post) do
%{
title: Faker.Lorem.sentence(),
body: Faker.Lorem.paragraph()
}
end
def params_for(Comment) do
%{
post: build(Post),
body: Faker.Name.paragraph()
}
end
def build(schema, params \\ []) do
struct!(schema, Enum.into(params, params_for(schema)))
end
def insert!(schema, params \\ []) do
fields = schema |> build(params) |> Foo.Repo.insert!() |> Map.take(schema.__schema__(:fields))
put_in(struct!(schema, fields).__meta__.state, :loaded)
end
end
# Examples:
import Foo.Factory
alias Blog.{Post, Comment}
params = params_for(Post)
post_1 = build(Post)
post_2 = build(Post, title: "Title I set on new post")
post_3 = insert!(Post)
post_4 = insert!(Post, title: "Title I set on inserted post")
comment_1 = insert!(Comment)
comment_2 = insert!(Comment, body: "A new post will be inserted with this comment")
comment_2 = insert!(Comment, post: post_1, body: "post_1 will be inserted with this comment")
comment_2 = insert!(Comment, post: post_3, body: "This will be associated to post_3")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment