【发布时间】:2017-12-07 00:18:41
【问题描述】:
我遇到了一个问题,像这样运行单个测试文件会通过:
mix test test/app_web/controllers/page_controller_test.exs
但运行整个测试套件会失败:
mix test
1) test GET / (AppWeb.PageControllerTest)
test/app_web/controllers/page_controller_test.exs:4
** (RuntimeError) expected response with status 200, got: 302, with body:
<html><body>You are being <a href="http://localhost:3000">redirected</a>.</body></html>
code: assert html_response(conn, 200) =~ "Welcome to Phoenix!"
stacktrace:
(phoenix) lib/phoenix/test/conn_test.ex:362: Phoenix.ConnTest.response/2
(phoenix) lib/phoenix/test/conn_test.ex:376: Phoenix.ConnTest.html_response/2
test/app_web/controllers/page_controller_test.exs:6: (test)
我不太确定发生了什么,但我的路由器中有一个插件,可以检查是否为所有传入请求设置了特定的 cookie。
所以我编辑了test/support/conn_case.ex 中的默认setup 以将该cookie 添加到conn。像这样(我的应用不需要数据库)。
setup do
token = Support.Token.generate_token()
conn =
ConnTest.build_conn()
|> ConnTest.put_req_cookie("session_token", token)
|> Plug.Conn.fetch_cookies()
{:ok, conn: conn}
end
有人知道发生了什么吗?
【问题讨论】:
-
当测试单独通过并在整个测试套件中失败时,通常意味着某些测试有副作用。请注意,默认情况下
ExUnit异步运行测试。您可能会通过将async: false选项传递给use ExUnit.Case, async: false来开始诊断。另外,请分享您的所有测试。 -
@mudasobwa 是的,你是对的。我在测试中使用
Application.set_env/3修改环境变量。 -
只需在
setup回调中使用context执行此操作。