I have found similar answers to this here and here, but it does not seem to be working.
I am having trouble assigning the current_user
to the session when testing. My tests are set up like this
setup do
%User{
id: 123456,
name: "MyName",
email: "abc@gmail.com",
password_hash: Comeonin.Bcrypt.hashpwsalt("password")
} |> Repo.insert
{:ok, user: Repo.get(User, 123456) }
end
and my test is
test "renders index.html on /coping-strategy", %{user: user} do
conn = conn
|> assign(:current_user, user)
|> get(coping_strategy_path(conn, :index))
assert html_response(conn, 200) =~ "Coping strategies"
end
When I inspect the conn here, current_user
has been correctly assigned to user
. However, when I inspect the conn in my controller during testing, current_user
is always nil
. I tried using build_conn
as well, but it is still nil.
Here is the controller:
def index(conn, _params) do
user_id = conn.assigns.current_user.id
coping_strategies = Post
|> Post.get_coping_strategies(user_id)
|> Repo.all
render conn, "index.html", coping_strategies: coping_strategies
end
If I try to assign something other than current_user, then it shows up when I inspect the conn in the controller. So if I added in |> assign(:stuff, "test")
in the test, then I have stuff: "test"
in assigns in the conn. If I change current_user
to current_user2
in the test and in the controller, it works because current_user2 updates and is passed along as I expect it to be.
Is there a reason I cannot assign the current user like this and why it is always nil? Are there any steps I am missing to do this for current_user in particular?
Aucun commentaire:
Enregistrer un commentaire