我正在关注一本书“Programming Phoenix >= 1.4”,却陷入了“测试注销用户”(集成测试,第 161 页)。测试失败。
video_controller_test.exs
defmodule RumblWeb.VideoControllerTest do
use RumblWeb.ConnCase, async: true
test "requires user authentication on all actions", %{conn: conn} do
Enum.each([
get(conn, Routes.video_path(conn, :new)),
get(conn, Routes.video_path(conn, :index)),
get(conn, Routes.video_path(conn, :show, "123")),
get(conn, Routes.video_path(conn, :edit, "123")),
put(conn, Routes.video_path(conn, :update, "123", %{})),
post(conn, Routes.video_path(conn, :create, %{})),
delete(conn, Routes.video_path(conn, :delete, "123")),
], fn conn ->
assert html_response(conn, 302)
assert conn.halted
end)
end
end
混合测试测试/rumbl_web
1) test requires user authentication on all actions (RumblWeb.VideoControllerTest)
test/rumbl_web/controllers/video_controller_test.exs:4
** (FunctionClauseError) no function clause matching in Rumbl.Multimedia.list_user_videos/1
The following arguments were given to Rumbl.Multimedia.list_user_videos/1:
# 1
nil
Attempted function clauses (showing 1 out of 1):
def list_user_videos(%Rumbl.Accounts.User{} = user)
code: get(conn, Routes.video_path(conn, :index)),
stacktrace:
(rumbl) lib/rumbl/multimedia.ex:107: Rumbl.Multimedia.list_user_videos/1
(rumbl) lib/rumbl_web/controllers/video_controller.ex:18: RumblWeb.VideoController.index/3
(rumbl) lib/rumbl_web/controllers/video_controller.ex:1: RumblWeb.VideoController.action/2
(rumbl) lib/rumbl_web/controllers/video_controller.ex:1: RumblWeb.VideoController.phoenix_controller_pipeline/2
(phoenix) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
(rumbl) lib/rumbl_web/endpoint.ex:1: RumblWeb.Endpoint.plug_builder_call/2
(rumbl) lib/rumbl_web/endpoint.ex:1: RumblWeb.Endpoint.call/2
(phoenix) lib/phoenix/test/conn_test.ex:225: Phoenix.ConnTest.dispatch/5
test/rumbl_web/controllers/video_controller_test.exs:7: (test)
Finished in 0.2 seconds
4 tests, 1 failure
Multimedia.list_user_videos/1
会用 nil
调用,并且没有这样的子句处理 nil
(它只需要用户结构。)
我相信
videos
资源应该通过 :authenticate_user
插头,就像 manage
那样。
我在这里找到了答案:
https://harfangk.github.io/2016/10/09/programming-phoenix-example-code-issues.html
如果测试“要求对所有操作进行用户身份验证”失败,则您很可能犯了与我类似的错误。检查你的 rumbl/web/router.ex 看看它是否像这样。
scope "/", Rumbl do
pipe_through :browser # Use the default browser stack
resources "/videos", VideoController
resources "/users", UserController, only: [:index, :show, :new, :create]
resources "/session", SessionController, only: [:new, :create, :delete]
get "/", PageController, :index
end
scope "/manage", Rumbl do
pipe_through [:browser, :authenticate_user]
resources "/videos", VideoController
end
删除该行
resources "videos", VideoController
在范围“/”中,Rumbl do …结束块。 您可能误读了生成资源第 6 章(PDF 第 92-93 页)中资源生成的输出结果,并将其理解为将资源“/videos”、VideoController 添加到 rumbl/web/router.ex 的指令。
注意:在最新的书中,“误读”部分位于生成 Web 界面,第 103 页。