你可能对 mix test test/tv_recipe/users_test.exs 命令已经烂熟于心。但 mix test test/tv_recipe_web/controllers/user_controller_test.exs 呢?
我们在生成用户的样板文件时,曾经生成过一个 user_controller_test.exs 文件,让我们运行下 mix test test/tv_recipe_web/controllers/user_controller_test.exs 看看结果:
$mixtesttest/tv_recipe_web/controllers/user_controller_test.exsCompiling1file (.ex)....1) test updates chosen resource and redirects when data is valid (TvRecipe.UserControllerTest)test/tv_recipe_web/controllers/user_controller_test.exs:47** (RuntimeError) expected redirection with status 302, got: 200stacktrace: (phoenix) lib/phoenix/test/conn_test.ex:443:Phoenix.ConnTest.redirected_to/2test/tv_recipe_web/controllers/user_controller_test.exs:50: (test)....2) test creates resource and redirects when data is valid (TvRecipe.UserControllerTest)test/tv_recipe_web/controllers/user_controller_test.exs:18** (RuntimeError) expected redirection with status 302, got: 200stacktrace: (phoenix) lib/phoenix/test/conn_test.ex:443:Phoenix.ConnTest.redirected_to/2test/tv_recipe_web/controllers/user_controller_test.exs:20: (test)Finishedin0.3seconds10tests,2failures
好消息是,10 个测试,有 8 个通过;坏消息是有 2 个未通过。
显然,从模板文件到现在,我们的代码已经变化,现在测试文件一样需要根据实际情况做调整:
diff --git a/test/tv_recipe_web/controllers/user_controller_test.exs b/test/tv_recipe_web/controllers/user_controller_test.exsindex 2e08483..95d3108 100644--- a/test/tv_recipe_web/controllers/user_controller_test.exs+++ b/test/tv_recipe_web/controllers/user_controller_test.exs@@ -2,7+2,7 @@ defmoduleTvRecipe.UserControllerTestdouseTvRecipe.ConnCasealiasTvRecipe.User- @valid_attrs %{email: "some content", password: "some content", username: "some content"}+ @valid_attrs %{email: "chenxsan@gmail.com", password: "some content", username: "chenxsan"} @invalid_attrs %{} test "lists all entries on index", %{conn: conn} do@@ -18,7+18,7 @@ defmoduleTvRecipe.UserControllerTestdo test "creates resource and redirects when data is valid", %{conn: conn} do conn = post conn,Routes.user_path(conn, :create), user: @valid_attrs assert redirected_to(conn) ==Routes.user_path(conn, :index)- assert Repo.get_by(User, @valid_attrs)+ assert Repo.get_by(User, @valid_attrs |>Map.delete(:password))end test "does not create resource and renders errors when data is invalid", %{conn: conn} do@@ -48,7+48,7 @@ defmoduleTvRecipe.UserControllerTestdo user =Repo.insert! %User{} conn = put conn,Routes.user_path(conn, :update, user), user: @valid_attrs assert redirected_to(conn) ==Routes.user_path(conn, :show, user)- assert Repo.get_by(User, @valid_attrs)+ assert Repo.get_by(User, @valid_attrs |>Map.delete(:password))end
我们在代码中做了三处修改,一个是订正 @valid_attrs,另外两个是修改 Repo.get,因为我们的 User 不再有 password 字段,所以应该从 @valid_attrs 中移除它,否则就会报错。