清理 ExUnit 测试示例

4

我在Phoenix应用中有以下测试:

defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  use TattooBackend.Web.ConnCase, async: true
  use Bamboo.Test

  alias TattooBackend.Web.Endpoint
  alias TattooBackend.Accounts.Account
  alias TattooBackend.Repo
  alias Phoenix.Token
  alias Comeonin.Bcrypt
  import TattooBackend.AuthenticationRequiredTest

  test "without passwords", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end

这些行在测试中被重复:

account = insert(:account)
token   = Token.sign(Endpoint, "account_id", account.id)

有什么想法能够使得它更加DRY吗?

您可能会喜欢ExUnit文档中的这个示例: https://hexdocs.pm/ex_unit/ExUnit.Callbacks.html#module-examples - Alisso
1个回答

4

如果你想在所有测试中执行这两行代码,可以将重复的代码放入setup回调中,并使用模式匹配来获取每个测试中的内容:

defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  ...

  setup do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    [account: account, token: token]
  end

  test "without passwords", %{conn: conn, account: account, token: token} do
    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn, account: account, token: token} do
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end

setup会在每个测试之前执行其代码,然后将accounttoken传递给每个测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接