Skip to content

Commit

Permalink
create test/app/person_test.exs to test basic Person CRUD #65
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Sep 30, 2020
1 parent 2d802dc commit b5baf20
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/app/person.ex
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
33 changes: 33 additions & 0 deletions test/app/person_test.exs
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

0 comments on commit b5baf20

Please sign in to comment.