Phoenix Elixir控制器单元测试Repo.get_by无法通过断言

时间:2016-06-21 12:19:56

标签: unit-testing elixir phoenix-framework

我在post_controller_test.exs中进行了单元测试:

test "creates resource and redirects when data is valid", %{conn: conn, user: user} do
        conn = post conn, user_post_path(conn, :create, user), post: @valid_attrs
        assert redirected_to(conn) == user_post_path(conn, :index, user)
        assert Repo.get_by(assoc(user, :posts), @valid_attrs)
    end

@valid_attrs是@valid_attrs %{body: "some content", title: "some content"}的简单值。我的postcontroller create() def:

def create(conn, %{"post" => post_params}) do
        changeset = 
            conn.assigns[:user]
            |> build_assoc(:posts)
            |> Post.changeset(post_params)

        case Repo.insert(changeset) do
            {:ok, _post} ->
                conn
                |> put_flash(:info, "Post created successfully.")
                |> redirect(to: user_post_path(conn, :index, conn.assigns[:user]))
            {:error, changeset} ->
                render(conn, "new.html", changeset: changeset)
        end
    end

测试传递重定向,但在assert Repo.get_by(assoc(user, :posts), @valid_attrs)失败。消息是预期truthy为零。我已经关联了用户模型的帖子:

field :username, :string
        field :email, :string
        field :password_digest, :string

        field :password, :string, virtual: true
        field :password_confirmation, :string, virtual: true
        timestamps

        has_many :posts, Pxblog.Post
    end

有人可以解释为什么测试无法通过吗?

0 个答案:

没有答案