Skip to content

Commit

Permalink
Raise if passing invalid keys to structs
Browse files Browse the repository at this point in the history
Closes #50
  • Loading branch information
paulcsmith committed Feb 26, 2016
1 parent 3fddb8f commit f2805f5
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ dependencies:
pre:
- wget http://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
- sudo apt-get update
- sudo apt-get install elixir=1.0.5-2
- sudo apt-get install elixir
- yes | mix deps.get
- mix local.rebar
test:
Expand Down
9 changes: 8 additions & 1 deletion lib/ex_machina.ex
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,14 @@ defmodule ExMachina do
"""
def build(module, factory_name, attrs \\ %{}) do
attrs = Enum.into(attrs, %{})
module.factory(factory_name) |> Map.merge(attrs)
module.factory(factory_name) |> do_merge(attrs)
end

defp do_merge(%{__struct__: _} = record, attrs) do
struct!(record, attrs)
end
defp do_merge(record, attrs) do
Map.merge(record, attrs)
end

@doc """
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule ExMachina.Mixfile do
[
app: :ex_machina,
version: @version,
elixir: "~> 1.0",
elixir: "~> 1.2",
description: "A factory library by the creators of FactoryGirl",
source_url: @project_url,
homepage_url: @project_url,
Expand Down
12 changes: 12 additions & 0 deletions test/ex_machina_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ defmodule ExMachinaTest do
}
end

def factory(:struct) do
%{
__struct__: Foo.Bar
}
end

def save_record(record) do
send self, {:custom_save, record}
record
Expand Down Expand Up @@ -78,6 +84,12 @@ defmodule ExMachinaTest do
}
end

test "build/2 raises if passing invalid keys to a struct factory" do
assert_raise KeyError, fn ->
Factory.build(:struct, doesnt_exist: true)
end
end

test "build_pair/2 builds 2 factories" do
records = Factory.build_pair(:user, admin: true)

Expand Down

0 comments on commit f2805f5

Please sign in to comment.