From 7f437113ea7abcb86fc6ff8349d73ba484e609ea Mon Sep 17 00:00:00 2001 From: Muhammad Surya Date: Sat, 6 Aug 2016 03:30:58 +0700 Subject: [PATCH] Drop fields that has nil values (#148) * 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 --- lib/ex_machina/ecto.ex | 8 ++++++++ test/ex_machina/ecto_test.exs | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/ex_machina/ecto.ex b/lib/ex_machina/ecto.ex index 6ff995b..dc164f3 100644 --- a/lib/ex_machina/ecto.ex +++ b/lib/ex_machina/ecto.ex @@ -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 """ @@ -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 @@ -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 diff --git a/test/ex_machina/ecto_test.exs b/test/ex_machina/ecto_test.exs index 13c4e90..2d988df 100644 --- a/test/ex_machina/ecto_test.exs +++ b/test/ex_machina/ecto_test.exs @@ -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) @@ -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