Skip to content

Commit

Permalink
Drop fields that has nil values (#148)
Browse files Browse the repository at this point in the history
* drop nil values

* add test for drop nil values

* make the intention a bit clearer by changing `Enum.filter` to Enum.reject

* move drop_nil_values/1 to be used in params_for and params_with_assocs. rename v to value

* add test for params_with_assocs/2 for params without nil values

* rename drop_nil_values/1 to drop_fields_with_nil_values/1 and improve test naming
  • Loading branch information
Fs02 authored and paulcsmith committed Aug 5, 2016
1 parent 5724796 commit 7f43711
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/ex_machina/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ defmodule ExMachina.Ecto do
def params_for(module, factory_name, attrs \\ %{}) do
module.build(factory_name, attrs)
|> drop_ecto_fields
|> drop_fields_with_nil_values
end

@doc """
Expand All @@ -90,6 +91,7 @@ defmodule ExMachina.Ecto do
module.build(factory_name, attrs)
|> insert_belongs_to_assocs(module)
|> drop_ecto_fields
|> drop_fields_with_nil_values
end

defp insert_belongs_to_assocs(record = %{__struct__: struct, __meta__: %{__struct__: Ecto.Schema.Metadata}}, module) do
Expand Down Expand Up @@ -133,4 +135,10 @@ defmodule ExMachina.Ecto do
{name, _type} -> Map.delete(map, name)
end
end

defp drop_fields_with_nil_values(map) do
map
|> Enum.reject(fn({_, value}) -> value == nil end)
|> Enum.into(%{})
end
end
14 changes: 14 additions & 0 deletions test/ex_machina/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ defmodule ExMachina.EctoTest do
end
end

test "params_for/2 removes fields with nil values" do
assert TestFactory.params_for(:user, admin: nil) == %{
name: "John Doe"
}
end

test "params_with_assocs/2 inserts belongs_tos that are set by the factory" do
assert has_association_in_schema?(ExMachina.Article, :editor)

Expand Down Expand Up @@ -83,6 +89,14 @@ defmodule ExMachina.EctoTest do
}
end

test "params_with_assocs/2 removes fields with nil values" do
assert has_association_in_schema?(ExMachina.User, :articles)

assert TestFactory.params_with_assocs(:user, admin: nil) == %{
name: "John Doe",
}
end

defp has_association_in_schema?(model, association_name) do
Enum.member?(model.__schema__(:associations), association_name)
end
Expand Down

0 comments on commit 7f43711

Please sign in to comment.