gpt4 book ai didi

elixir - 清理 ExUnit 测试示例

转载 作者:行者123 更新时间:2023-12-02 07:13:17 26 4
gpt4 key购买 nike

我在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)

知道如何让它更干燥吗?

最佳答案

如果您想在所有测试中执行这两行,您可以将重复代码放入 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 传递给每个测试。

关于elixir - 清理 ExUnit 测试示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com