How to pass a anonymous function to ExUnit test

This is a sample of my test:

Enum.each([:memory, :mongodb], fn(provider) ->
  @tag provider: provider
  describe "given a #{provider} repository" do
    test("index/2 responds with all Resources", %{conn: conn}, do: index(conn))
  end
end)

def index(conn) do
  conn
  |> get(resource_path(conn, :index))
  |> json_response(200)
end

There is any way to pass the index function direct to the test? Something like this:

test("index/2 responds with all Resources", &index/1)

Tried this and &__MODULE__.index/1, but it does not work. It print at the console the test title, but don’t execute the function.

Strictly speaking it is possible to pass function to test:

describe "test" do
  setup do
    {:ok, %{my_fun: &my_function/0}}
  end

  test "My test case", %{my_fun: fun} do
    IO.puts fun.()
  end

  def my_function do
    "Hello, cruel world!" 
  end
end

May I ask what are you trying to accomplish?

2 Likes

Nevermind, just realized that i don’t need this anymore. The problem is, my application can have multiple implementations of the repository (in-memory, mongodb, etc…). I need to test if all implementations have the same behaviour.

I was duplicating the code until i realized that i could loop (Enum.each([:memory, :mongodb], fn(provider) ->) trough all the tests for each provider, so i can just declare the test function inside the test instead of call another function to test it.

Thanks anyway.

1 Like