From 3322badb3643b1cc8d184c26aa462f6f0370a2f8 Mon Sep 17 00:00:00 2001 From: Glen Holcomb Date: Thu, 14 Dec 2017 11:55:17 -0700 Subject: [PATCH] =?UTF-8?q?Actually=20create=20a=20`Source`=20for=20every?= =?UTF-8?q?=20=E2=80=9Cperson=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/edges/events/action.ex | 6 ++++- mix.exs | 2 +- test/edges/events/action_test.exs | 43 +++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 test/edges/events/action_test.exs diff --git a/lib/edges/events/action.ex b/lib/edges/events/action.ex index 6c0e0a9..e60a90d 100644 --- a/lib/edges/events/action.ex +++ b/lib/edges/events/action.ex @@ -27,7 +27,9 @@ defmodule Edges.Events.Action do """ use Ecto.Schema + import Ecto.Changeset + import Ecto.Query alias __MODULE__ alias Edges.Events.Source @@ -66,7 +68,9 @@ defmodule Edges.Events.Action do attrs |> Map.get(:person) - Repo.one(Source, person: person) || + source_query = from(s in Source, where: s.person == ^person) + + Repo.one(source_query) || Repo.insert!(%Source{person: person}) end diff --git a/mix.exs b/mix.exs index 6c00a55..67fee9b 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Edges.Mixfile do def project do [ app: :edges, - version: "0.1.0", + version: "0.2.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, elixirc_paths: elixirc_paths(Mix.env), diff --git a/test/edges/events/action_test.exs b/test/edges/events/action_test.exs new file mode 100644 index 0000000..97157bc --- /dev/null +++ b/test/edges/events/action_test.exs @@ -0,0 +1,43 @@ +defmodule Edges.Events.ActionTest do + use ExUnit.Case + + alias Edges.Events.Action + alias Edges.Events.Source + alias Edges.Repo + + setup do + :ok = Ecto.Adapters.SQL.Sandbox.checkout(Edges.Repo) + + {:ok, source} = + %Source{} + |> Source.changeset(%{person: "test source"}) + |> Repo.insert() + + {:ok, existing_source: source} + end + + describe "Action Creation" do + test "creating for an existing person uses that source", %{existing_source: source} do + person = source.person() + source_id = source.id() + + {:ok, action} = + %Action{} + |> Action.changeset(%{action: "Favorited", resource_type: "Listing", resource_id: "42", person: person}) + |> Repo.insert() + + assert ^source_id = action.source_id() + end + + test "creating for a new person creates a new source", %{existing_source: source} do + existing_id = source.id() + + {:ok, action} = + %Action{} + |> Action.changeset(%{action: "Favorites", resource_type: "Listing", resource_id: "42", person: "new guy"}) + |> Repo.insert() + + refute existing_id == action.source_id() + end + end +end