Skip to content

Fixes for Blog.Accounts.create_user/1 #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions lib/blog/accounts/accounts.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ defmodule Blog.Accounts do
with {:ok, contact} <- create_contact(contact_attrs),
{:ok, user} <- do_create_user(user_attrs, contact) do
%{user | contacts: [contact]}
else
{:error, changeset} ->
Repo.rollback(changeset)
end
end

Expand All @@ -21,14 +24,14 @@ defmodule Blog.Accounts do
def create_contact(attrs) do
attrs
|> Accounts.Contact.changeset
|> Blog.Repo.insert
|> Repo.insert
end

defp do_create_user(attrs, contact) do
attrs
|> Map.put(:contact_id, contact.id)
|> Accounts.User.changeset
|> Blog.Repo.insert
|> Repo.insert
end

end
1 change: 1 addition & 0 deletions lib/blog/accounts/contact.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ defmodule Blog.Accounts.Contact do
contact
|> cast(attrs, [:type, :value])
|> validate_required([:type, :value])
|> unique_constraint(:value, name: :contacts_type_value_index)
end

end
27 changes: 27 additions & 0 deletions test/blog/accounts/accounts_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
defmodule Blog.AccountsTest do
use Blog.DataCase

alias Blog.Accounts

test "create_user/1 returns {:error, changeset} and rolles back transaction on error" do
attrs = %{
contact: %{type: "phone", value: "+1 000 000 0000"},
name: "",
password: "password"
}

contact_count = Repo.aggregate(Accounts.Contact, :count, :id)

assert {:error, %Ecto.Changeset{}} = Accounts.create_user(attrs)
assert ^contact_count = Repo.aggregate(Accounts.Contact, :count, :id)
end

test "create_user/1 discards duplicate contacts" do
contact = %{type: "phone", value: "+1 000 000 0000"}

assert {:ok, _} = Accounts.create_user(%{contact: contact, name: "name", password: "password"})

assert {:error, changeset} = Accounts.create_user(%{contact: contact, name: "other", password: "password"})
assert "has already been taken" in errors_on(changeset).value
end
end