在会话中分配当前用户进行测试 [英] Assign current user in session for tests
问题描述
我已经找到与此在这里,但似乎不起作用.
I have found similar answers to this here and here, but it does not seem to be working.
在测试时,我很难将current_user
分配给会话.我的测试是这样设置的
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
我的测试是
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
当我在此处检查conn时,已将current_user
正确分配给<c2>.但是,在测试过程中检查控制器中的conn时,current_user
始终为nil
.我也尝试使用build_conn
,但它仍然为零.
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.
这是控制器:
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
如果我尝试分配除current_user以外的其他内容,则在检查控制器中的conn时会显示该内容.因此,如果我在测试中添加了|> assign(:stuff, "test")
,则conn中的赋值中将包含stuff: "test"
.如果我在测试和控制器中将current_user
更改为current_user2
,它会起作用,因为current_user2会更新并按照我期望的方式传递.
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.
有没有原因不能像这样分配当前用户,为什么它始终为nil?特别是对于current_user,我缺少任何步骤要做吗?
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?
修改
在此处在auth插件中设置current_user
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
推荐答案
由于您是在测试中的assigns
中直接设置:current_user
,因此如果:current_user
:
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
这篇关于在会话中分配当前用户进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!