I'm facing the problem where all tests in which I need to assert more than one thing with a logged in user, it seems that it loses the saved session.
I have a setup code which assigns a fixture user before each test:
setup %{conn: conn} = config do
if username = config[:login_as] do
user = insert_user(username: username)
conn = assign(conn, :current_user, user)
{:ok, conn: conn, user: user}
else
:ok
end
end
All my tests which happen in the logged-in area take the tag login_as: "username"
.
@tag login_as: "max"
test "redirects to show when data is valid", %{conn: conn} do
conn = post conn, debit_event_path(conn, :create), debit_event: @create_attrs
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == debit_event_path(conn, :show, id) #1
conn = get conn, debit_event_path(conn, :show, id)
assert html_response(conn, 200) =~ "Show Debit event" #2
end
The first assertion (#1 comment in code) always works, but for some reason, the second assertion (#2 comment in code) fails and it behaves as if my user was logged out. It happens in all cases where I need to persist the user between requests.
Is there a correct approach to have this data persisted across tests requests as it was a browser request?
conn
, thus theconn = post conn...
overrides the one assigned intest "...", %{conn: conn}
, and later used inconn = get conn...
. You could either separate the cases to separate tests, to try renaming theconn
that is modified by requests eg:resp_conn = post conn...
and thenassert redirected_to(resp_conn) == ...
. The same thing forresp_conn = get conn
, so the originalconn
is used to initiate the request/response, but the effect would be assigned to a fresh variable and not re-used for next request. Does it make sense?