在用户#show中测试“某些内容”

时间:2016-04-30 11:40:51

标签: elixir phoenix-framework

我有以下凤凰申请:

mix phoenix.new my_app --database mysql
cd my_app
mix ecto.create
mix phoenix.gen.html User users name:string
mix ecto.migrate

现在mix test没有遇到问题。

如果我将test/controllers/user_controller_test.exs更改为期望“某些内容”而不是show中的“显示用户”,因为@valid_attrs %{name: "some content"}而应该存在,而不是测试失败。为什么会这样? user#show页面上应该包含“部分内容”。当我在development模式下在浏览器中手动尝试时,它就有了。

错误在哪里?我该如何解决?

测试/控制器/ user_controller_test.exs

defmodule MyApp.UserControllerTest do
  use MyApp.ConnCase

  alias MyApp.User
  @valid_attrs %{name: "some content"}
  @invalid_attrs %{}

  [...]

  test "shows chosen resource", %{conn: conn} do
    user = Repo.insert! %User{}
    conn = get conn, user_path(conn, :show, user)
    assert html_response(conn, 200) =~ "some content"
  end

  [...]

测试输出

$ mix test
........

  1) test shows chosen resource (MyApp.UserControllerTest)
     test/controllers/user_controller_test.exs:29
     Assertion with =~ failed
     code: html_response(conn, 200) =~ "some content"
     lhs:  "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <meta name=\"description\" content=\"\">\n    <meta name=\"author\" content=\"\">\n\n    <title>Hello MyApp!</title>\n    <link rel=\"stylesheet\" href=\"/css/app.css\">\n  </head>\n\n  <body>\n    <div class=\"container\">\n      <header class=\"header\">\n        <nav role=\"navigation\">\n          <ul class=\"nav nav-pills pull-right\">\n            <li><a href=\"http://www.phoenixframework.org/docs\">Get Started</a></li>\n          </ul>\n        </nav>\n        <span class=\"logo\"></span>\n      </header>\n\n      <p class=\"alert alert-info\" role=\"alert\"></p>\n      <p class=\"alert alert-danger\" role=\"alert\"></p>\n\n      <main role=\"main\">\n        <h2>Show user</h2>\n\n<ul>\n\n  <li>\n    <strong>Name:</strong>\n    \n  </li>\n\n</ul>\n\n<a href=\"/users/16/edit\">Edit</a>\n<a href=\"/users\">Back</a>\n\n      </main>\n\n    </div> <!-- /container -->\n    <script src=\"/js/app.js\"></script>\n  </body>\n</html>\n"
     rhs:  "some content"
     stacktrace:
       test/controllers/user_controller_test.exs:32

.......

Finished in 0.4 seconds (0.2s on load, 0.1s on tests)
16 tests, 1 failure

Randomized with seed 734322

1 个答案:

答案 0 :(得分:1)

该行

user = Repo.insert! %User{}

将所有字段设置为nil的用户插入。

如果您要使用@valid_attrs创建用户,请将该行更改为:

user = Repo.insert! User.changeset(%User{}, @valid_attrs)