Skip to content

Instantly share code, notes, and snippets.

@bryanjos
Created May 7, 2019 18:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjos/83f155bab276a8d3a93cdc552b3134d9 to your computer and use it in GitHub Desktop.
Save bryanjos/83f155bab276a8d3a93cdc552b3134d9 to your computer and use it in GitHub Desktop.
StreamData x ExMachina
defmodule AppTemplate.Factory do
alias AppTemplate.{Repo}
use ExMachina.Ecto, repo: Repo
alias AppTemplate.Generators
def user_factory do
Generators.generate(:user)
end
end
defmodule AppTemplate.Generators do
@moduledoc """
Holds generator functions to provide generative data for testing
For generators offered by StreamData, check here:
https://hexdocs.pm/stream_data
"""
use ExUnitProperties
alias AppTemplate.{
User
}
def generator(:user) do
gen all email <- generator(:email) do
%User{
email: email,
password: Bcrypt.hash_pwd_salt("password")
}
end
end
def generator(:email) do
gen all local <- string(:alphanumeric, min_length: 1),
domain <- string(:alphanumeric, min_length: 1) do
String.downcase(local <> to_string(System.unique_integer()) <> "@" <> domain)
end
end
def generate(generator_name, attributes \\ []) do
1 |> generate_list(generator_name, attributes) |> List.first()
end
def generate_list(count, generator_name, attributes \\ []) do
generator_name
|> apply_attrs_to_generator(attributes)
|> Enum.take(count)
end
defp apply_attrs_to_generator(generator_name, attributes) do
generator_name
|> generator
|> Stream.map(&struct(&1, attributes))
end
def generate_string(max_length) do
length = Enum.random(1..max_length)
length |> :crypto.strong_rand_bytes() |> Base.url_encode64() |> binary_part(0, length)
end
end
defmodule AppTemplate.Users.Test do
use AppTemplate.DataCase, async: true
alias AppTemplate.Users
test "create" do
{:ok, user} =
Users.create_user(%{
"email" => "joe@example.com",
"new_password" => "hi",
"new_password_confirmation" => "hi"
})
assert user.email == "joe@example.com"
end
test "get_user_by_email" do
user = insert(:user)
user_from_db = Users.get_user_by_email(user.email)
assert user.email == user_from_db.email
end
test "get_user" do
user = insert(:user)
user_from_db = Users.get_user(user.id)
assert user.email == user_from_db.email
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment