Phoenix-Elixir在测试期间指定不在eex模板中

时间:2016-06-02 02:00:58

标签: elixir phoenix-framework

我正在使用Phoenix网络框架学习Elixir。我自己已经走得很远了,但是在我遇到困难的测试中我遇到了一个错误。该错误仅在测试期间发生,而不是在实际运行应用程序时发生。

错误:

  1) test does not create resource and renders errors when data is invalid (Potion.CommentControllerTest)
     test/controllers/comment_controller_test.exs:25
     ** (ArgumentError) assign @num_approved_comments not available in eex template.

comment_controller_test.exs

defmodule Potion.CommentControllerTest do
  use Potion.ConnCase

  alias Potion.Comment
  alias Potion.Factory

  @valid_attrs %{author: "Some Person", body: "This is a sample comment"}
  @invalid_attrs %{}

  setup do
    user = Factory.create(:user)
    post = Factory.create(:post, user: user)
    comment = Factory.create(:comment, post: post)

    {:ok, conn: conn, user: user, post: post, comment: comment}
  end

  test "does not create resource and renders errors when data is invalid", %{conn: conn, post: post} do
    conn = post conn, post_comment_path(conn, :create, post), comment: @invalid_attrs
    assert html_response(conn, 200) =~ "Oops, something went wrong"
  end

  # privates
  defp login_user(conn, user) do
    post conn, session_path(conn, :create), user: %{username: user.username, password: user.password}
  end

end

1 个答案:

答案 0 :(得分:1)

失败的测试是测试CommentController的create动作,而不是PostController的show动作。

您的创建操作不包括@num_approved_comments in assigns:

  def create(conn, %{"comment" => comment_params, "post_id" => post_id}) do
    # Find the post and preload nav props
    post = Repo.get!(Post, post_id) |> Repo.preload([:user, :comments])

    # Build the changeset
    changeset = post
      |> build_assoc(:comments)
      |> Comment.changeset(comment_params)

    case Repo.insert(changeset) do
      # Inserted successfully
      {:ok, _comment} ->
        conn
        |> put_flash(:info, "Comment created successfully!")
        |> redirect(to: user_post_path(conn, :show, post.user, post))
      # Error on insert
      {:error, changeset} ->
        render(conn, Potion.PostView, "show.html", post: post, user: post.user,
        comment_changeset: changeset)
    end
  end