Skip to content

Commit

Permalink
Build assocations instead of creating them
Browse files Browse the repository at this point in the history
  • Loading branch information
jsteiner committed Oct 9, 2015
1 parent a25f622 commit b518285
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
16 changes: 8 additions & 8 deletions lib/ex_machina/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 """
Expand Down
13 changes: 6 additions & 7 deletions test/ex_machina/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -123,24 +123,23 @@ 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
attrs = %{}

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
Expand Down

0 comments on commit b518285

Please sign in to comment.