I had this unit test in 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 are simple value of @valid_attrs %{body: "some content", title: "some content"}. And my 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
Test pass on redirect, but failed on assert Repo.get_by(assoc(user, :posts), @valid_attrs). Message is expected truthy got nil. I already have assoc with posts on user model:
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
Can anyone explain why that test cannot pass?
Aucun commentaire:
Enregistrer un commentaire