gpt4 book ai didi

elixir - 测试 Phoenix - 如果有 foreign_key 约束,是否仍然使用@valid_attrs?

转载 作者:行者123 更新时间:2023-12-02 04:39:12 28 4
gpt4 key购买 nike

在大多数模型测试中,您可以访问 @valid_attrs ,它允许简单地创建模型,而不必不断地复制/键入参数。

如果我有 user_id 约束(不能是随机数,因为 ID 已经过验证)

反正还有用@valid_attrs吗?

现在,我正在我的 setup 中创建一个用户 block ,然后 Map.put(@valid_attrs, :user_id, user.id)当我需要的时候。像这样:

defmodule ModelTest do
# Not really valid without user_id
@valid_attrs %{name: "some content"}
@invalid_attrs %{}

setup do
{:ok, user} = User.registration_changeset(User{}, %{username: "tester_user", email: "tester@test.com", password: "Password", password_confirmation: "Password"}) |> Repo.insert
{:ok, %{user: user}}
end

test "some test", %{user: user} do
{:ok, room} = Model.changeset(%Room{}, Map.put(@valid_attrs, :user_id, user.id)) |> Repo.insert
## test stuff
end
end

有点乱,有没有更干净的方法来做到这一点?

最佳答案

简短回答

我不会说你有什么乱七八糟的,但我猜你想使用 valid_attrs在多次测试中。你可以把 user_idvalid_attrs并在 setup 中返回堵塞:

defmodule ModelTest do
# Not really valid without user_id
@valid_attrs %{name: "some content"}
@invalid_attrs %{}

setup do
{:ok, user} = User.registration_changeset(User{}, %{username: "tester_user", email: "tester@test.com", password: "Password", password_confirmation: "Password"}) |> Repo.insert
valid_attrs = Map.put(@valid_attrs, :user_id, user.id)
{:ok, %{user: user, valid_attrs: valid_attrs}}
end

test "some test", %{user: user, valid_attrs: valid_attrs} do
{:ok, room} = Model.changeset(%Room{}, valid_attrs) |> Repo.insert
## test stuff
end
end

长答案

来自 Programming Phoenix (我强烈推荐阅读):

In Phoenix, whenever it’s possible, we try to limit side effects—functions that touch and possibly change the outside world—to the controller. We’ll try to keep the functions in our models and views pure, so that calling the same function with the same arguments will always yield the same results.

If you’re a diehard MVC person, you might have to reimagine the job of the model layer. In Phoenix, you’ll want to separate the code that calls another web server, or fetches code from a database, from the code that processes that data. We process data in the model; we read or write that data through the controller. Ecto allows us to organize our code in this way. It separates the code with side effects, which changes the world around us, from the code that’s only transforming data.



基于此,我建议不要在模型测试中测试 foreign_key 约束,而是在 Controller 测试(或单独的“模型”测试)中测试。在模型测试中,您可以只验证 user_id 的存在。 (通过在您的 user_id: 1 中包含 @valid_attrs )。

以下是在 Programming Phoenix 中构建的示例应用程序中如何测试约束(在本例中为 unique_constraint,但同样可以应用于任何约束)。在 User Model ,有一个 unique_constraintusername .用户模型的测试在 2 个独立的测试模块中完成:
  • UserTest unique_constraint没有经过测试,也没有调用 repo ;
  • UserRepoTest调用 Repo 以专门测试约束。
  • 关于elixir - 测试 Phoenix - 如果有 foreign_key 约束,是否仍然使用@valid_attrs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897458/

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