I’m in the process of creating some reusable test modules using a macro:
defmodule SharedTestCase do
defmacro define_tests(do: block) do
quote do
defmacro __using__(options) do
block = unquote(Macro.escape(block))
quote do
use ExUnit.Case
@moduletag unquote(options)
unquote(block)
end
end
end
end
end
I’ve gotten as far as defining a reusable method for post/3
requests, but would like to extend to supply the verb as a method. I’m unsure how to invoke the methods supplied by Phoenix.ConnTest
dynamically as Kernel.apply/3
expects a module as the first argument. Here is a working example for post requests:
defmodule EnsureAuthenticatedConnTests do
import SharedTestCase
define_tests do
test "returns an error when the connection has no form of authentication", %{data: data, route: route} do
assert %{
"errors" => [%{
"message" => "Unauthorized"
}]
} == build_conn()
|> put_req_header("accept", "application/json")
|> post(route, data)
|> json_response(401)
end
end
end
Ideally, post
becomes a method invoked by Kernel.apply/3
. Using the module:
defmodule MyApp.SomeControllerTest do
use MyApp.ConnCase
use EnsureAuthenticatedConnTests, data: %{"foo" => "bar}, route: "/users"
end
Any thoughts would be appreciated!