0
votes

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: "[email protected]",
    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?

Edit

Here's where current_user is being set in the auth plug

def call(conn, repo) do
  user_id = get_session(conn, :user_id)
  user = user_id && repo.get(Healthlocker.User, user_id)
  assign(conn, :current_user, user)
end
1
Can you post the code that assigns current_user in your app (authentication plug?)? You're probably setting it to nil even if it's already set.Dogbert
@Dogbert that looks like it. user is nil when I'm running the tests.Katherine

1 Answers

3
votes

Since you're directly setting :current_user in assigns in the tests, you need to skip fetching the user from the session's :user_id if assigns contains :current_user in the auth plug:

def call(conn, repo) do
  if conn.assigns[:current_user] do
    conn
  else
    user_id = get_session(conn, :user_id)
    user = user_id && repo.get(Healthlocker.User, user_id)
    assign(conn, :current_user, user)
  end
end