-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create test/app/person_test.exs to test basic Person CRUD #65
- Loading branch information
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
defmodule App.Person do | ||
use Ecto.Schema | ||
import Ecto.Changeset | ||
alias App.Repo | ||
# https://stackoverflow.com/a/47501059/1148249 | ||
alias __MODULE__ | ||
|
||
schema "people" do | ||
field :status, :id | ||
field :tag, :id | ||
timestamps() | ||
end | ||
|
||
@doc """ | ||
Default attributes validation for Person | ||
""" | ||
def changeset(person, attrs) do | ||
person | ||
|> cast(attrs, [:id, :status, :tag]) | ||
end | ||
|
||
def create_person(attrs) do | ||
changeset(%Person{}, attrs) | ||
|> Repo.insert!() | ||
end | ||
|
||
def get_person!(id) do | ||
__MODULE__ | ||
|> Repo.get_by!(id: id) | ||
end | ||
|
||
def upsert_person(person) do | ||
case get_person!(person.id) do | ||
nil -> | ||
create_person(person) | ||
|
||
# existing person | ||
ep -> | ||
merged = Map.merge(AuthPlug.Helpers.strip_struct_metadata(ep), person) | ||
{:ok, person} = Repo.update(changeset(%Person{id: ep.id}, merged)) | ||
# ensure that the preloads are returned: | ||
person | ||
end | ||
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
defmodule App.CtxTest do | ||
use App.DataCase | ||
alias App.Person | ||
|
||
describe "people" do | ||
@valid_attrs %{ | ||
status: 1, | ||
} | ||
@update_attrs %{ | ||
status: 2 | ||
} | ||
|
||
test "create_person/1 with valid data creates a person" do | ||
person = Person.create_person(@valid_attrs) | ||
assert person.status == 1 | ||
end | ||
|
||
test "get_person!/1 returns the person with given id" do | ||
person = create_person() | ||
got_person = Person.get_person!(person.id) | ||
|
||
assert got_person.id == person.id | ||
end | ||
|
||
test "usert_person/1 with valid data updates the person" do | ||
person = create_person() | ||
update_data = Map.merge(@update_attrs, %{id: person.id}) | ||
updated_person = Person.upsert_person(update_data) | ||
|
||
assert updated_person.status == @update_attrs.status | ||
end | ||
end | ||
end |