Hello
Im looking for a way to improve my controller tests. Currently I am doing something like this
test "lists all menu_items", %{conn: conn, user: user} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.menu_item_path(conn, :index))
assert html_response(conn, 200) =~ "some html"
end
To setup the user record I tried using this aproach (Using setup_all with database?) but I ran into some database errors when running all tests.
I could use setup
instead of setup_all
but that makes the test suite very slow.
Another aproach I tried was implementing mocks as José describe here
defmodule MyApp.LoggedUserCase do
use ExUnit.CaseTemplate
require Ecto.Query
setup do
user = Application.get_env(:my_app, :session_plug_account_module).get_user!(123)
{:ok, user: user}
end
end
But some coworkers found it awkward to call Application.get_env(:my_app, :session_plug_account_module)
on the authentication plug because it sounds like you are changing code just for the sake of the tests, I dont have a problem with it but others have.
The first attempt was to put some condition on the router to ignore the auth plug but it looks ugly/wrong as hell
pipeline :authenticated do
if Mix.env() != :test do
plug MyApp.Plugs.RequireSessionStatus, :authenticated
end
end