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))

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

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}}

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

  def my_function do
    "Hello, cruel world!" 

May I ask what are you trying to accomplish?


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