Skip to content

Commit

Permalink
handle the number 0 in build_list and insert_list
Browse files Browse the repository at this point in the history
fixes #231
  • Loading branch information
alxgnon authored and jsteiner committed Jul 18, 2017
1 parent e3e2447 commit 012e957
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 7 deletions.
11 changes: 6 additions & 5 deletions lib/ex_machina.ex
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ defmodule ExMachina do
ExMachina.build_pair(__MODULE__, factory_name, attrs)
end

def build_list(number_of_factories, factory_name, attrs \\ %{}) do
ExMachina.build_list(__MODULE__, number_of_factories, factory_name, attrs)
def build_list(number_of_records, factory_name, attrs \\ %{}) do
ExMachina.build_list(__MODULE__, number_of_records, factory_name, attrs)
end

@spec create(any) :: no_return
Expand Down Expand Up @@ -179,10 +179,11 @@ defmodule ExMachina do
# Returns a list of 3 users
build_list(3, :user)
"""
def build_list(module, number_of_factories, factory_name, attrs \\ %{}) do
Enum.map 1..number_of_factories, fn(_) ->
def build_list(module, number_of_records, factory_name, attrs \\ %{}) do
Stream.repeatedly(fn ->
ExMachina.build(module, factory_name, attrs)
end
end)
|> Enum.take(number_of_records)
end

defmacro __before_compile__(_env) do
Expand Down
5 changes: 3 additions & 2 deletions lib/ex_machina/strategy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ defmodule ExMachina.Strategy do
end

def unquote(:"#{function_name}_list")(number_of_records, factory_name, attrs \\ %{}) do
Enum.map 1..number_of_records, fn(_) ->
Stream.repeatedly(fn ->
unquote(function_name)(factory_name, attrs)
end
end)
|> Enum.take(number_of_records)
end
end
end
Expand Down
4 changes: 4 additions & 0 deletions test/ex_machina/ecto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ defmodule ExMachina.EctoTest do
assert [%User{}, %User{}, %User{}] = TestFactory.insert_list(3, :user, admin: true)
end

test "insert_list/3 handles the number 0" do
assert [] = TestFactory.insert_list(0, :user)
end

test "params_for/2 removes Ecto specific fields" do
assert TestFactory.params_for(:user) == %{
name: "John Doe",
Expand Down
4 changes: 4 additions & 0 deletions test/ex_machina_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ defmodule ExMachinaTest do
assert records == [expected_record, expected_record, expected_record]
end

test "build_list/3 handles the number 0" do
assert [] = Factory.build_list(0, :user)
end

test "raises helpful error when using old create functions" do
assert_raise RuntimeError, ~r/create\/1 has been removed/, fn ->
Factory.create(:user)
Expand Down

0 comments on commit 012e957

Please sign in to comment.