From b518285fa144459c36848bda5e72498914c19cdd Mon Sep 17 00:00:00 2001 From: Josh Steiner Date: Fri, 2 Oct 2015 15:54:34 -0400 Subject: [PATCH] Build assocations instead of creating them --- lib/ex_machina/ecto.ex | 16 ++++++++-------- test/ex_machina/ecto_test.exs | 13 ++++++------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/lib/ex_machina/ecto.ex b/lib/ex_machina/ecto.ex index be41ab4..6303382 100644 --- a/lib/ex_machina/ecto.ex +++ b/lib/ex_machina/ecto.ex @@ -73,7 +73,7 @@ defmodule ExMachina.Ecto do end @doc """ - Gets a factory from the passed in attrs, or creates if none is present + Gets a factory from the passed in attrs, or builds if none is present ## Examples @@ -82,25 +82,25 @@ defmodule ExMachina.Ecto do assoc(:user) attrs = %{} - # Creates and returns new instance based on :user factory + # Builds and returns new instance based on :user factory assoc(:user) attrs = %{} - # Creates and returns new instance based on :user factory + # Builds and returns new instance based on :user factory assoc(:author, factory: :user) """ def assoc(module, attrs, factory_name, opts \\ []) do case Map.get(attrs, factory_name) do - nil -> create_assoc(module, factory_name, opts) + nil -> build_assoc(module, factory_name, opts) record -> record end end - defp create_assoc(module, _factory_name, factory: factory_name) do - ExMachina.create(module, factory_name) + defp build_assoc(module, _factory_name, factory: factory_name) do + ExMachina.build(module, factory_name) end - defp create_assoc(module, factory_name, _opts) do - ExMachina.create(module, factory_name) + defp build_assoc(module, factory_name, _opts) do + ExMachina.build(module, factory_name) end @doc """ diff --git a/test/ex_machina/ecto_test.exs b/test/ex_machina/ecto_test.exs index 932cc3d..b0fa3bd 100644 --- a/test/ex_machina/ecto_test.exs +++ b/test/ex_machina/ecto_test.exs @@ -123,15 +123,14 @@ defmodule ExMachina.EctoTest do TestRepo.all(User) == [] end - test "assoc/3 creates and returns a factory if one was not in attrs" do + test "assoc/3 builds and returns a factory if one was not in attrs" do attrs = %{} user = ExMachina.Ecto.assoc(EctoFactories, attrs, :user) - newly_created_user = TestRepo.one!(User) - assert newly_created_user.name == "John Doe" - refute newly_created_user.admin - assert user == newly_created_user + refute TestRepo.one(User) + assert user.name == "John Doe" + refute user.admin end test "assoc/3 can specify a factory for the association" do @@ -139,8 +138,8 @@ defmodule ExMachina.EctoTest do account = ExMachina.Ecto.assoc(EctoFactories, attrs, :account, factory: :user) - new_user = TestRepo.one!(User) - assert account == new_user + assert account == EctoFactories.build(:user) + refute TestRepo.one(User) end test "can use assoc/3 in a factory to override associations" do