elixir - 测试 Elixir Ecto 模型关联的最佳实践

标签 elixir phoenix-framework ecto

我正在尝试在 Elixir 中测试属于关联。

假设我有两个模型,一个 Product 和一个 ProductType。产品属于一种产品类型。

defmodule Store.Product do
  use Store.Web, :model

  schema "products" do
    field :name, :string

    belongs_to :type, Store.ProductType, foreign_key: :product_type_id

    timestamps
  end

  @required_fields ~w(name product_type_id)

  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

defmodule Store.ProductType do
  use Store.Web, :model

  schema "product_types" do
    field :name, :string

    timestamps
  end

  @required_fields ~w(name)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

这是我的测试文件中的内容:

defmodule Store.ProductTest do
  use Store.ModelCase

  alias Store.Repo
  alias Store.Product
  alias Store.ProductType

  @valid_attrs %{
    name: "pickles", 
    product_type_id: 42,
  }

  @invalid_attrs %{}

  test "product type relationship" do
    product_type_changeset = ProductType.changeset(
      %ProductType{}, %{name: "Foo"}
    )
    product_type = Repo.insert!(product_type_changeset)

    product_changeset = Product.changeset(
      %Product{}, %{@valid_attrs | product_type_id: product_type.id}
    )
    product = Repo.insert!(product_changeset)

    product = Product |> Repo.get(product.id) |> Repo.preload(:type)
    assert product_type == product.type
  end
end

我基本上是在创建一个产品类型,创建一个产品,从数据库中获取产品记录并验证该类型与我创建的类型是否相同。

这是一个合理的方法吗?

编辑

为了后代的缘故,这里有一个更清晰的测试,不使用变更集:

test "belongs to product type" do
  product_type = Repo.insert!(%ProductType{})
  product = Repo.insert!(%Product{product_type_id: product_type.id})
  product = Product |> Repo.get(product.id) |> Repo.preload(:type)
  assert product_type == product.type
end

要测试此关联,您基本上可以放弃转换和验证。

最佳答案

我根本不会明确地测试这个——你基本上是在这里测试 Ecto。

这种事情我通常在例如隐式测试 Controller 测试,您可以在其中发布一些内容,然后确保在数据库中创建了正确的数据。

如果您想为此进行单元测试,您需要考虑到底要比较什么。测试插入的产品类型的 id 是否与插入的产品的 product_type_id 相同应该就足够了,但这感觉很奇怪,因为这样更明显的是,您只是在此处测试 ecto 功能。

关于elixir - 测试 Elixir Ecto 模型关联的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928804/

相关文章:

ubuntu - 如何安装 esl-erlang、erlang-crypto 和 erlang-tools?

elixir - 如何添加条件必填字段?

runtime-error - 在 elixir 1.3.2 中运行 phoenix 测试的所有权进程错误

elixir - 引脚 (^) 运算符的使用困惑

elixir - Elixir 如何读取远程节点 mnesia 表

mysql - Ecto 2.0 + MySQL : cleaning fixtures in tests

elixir - Ecto过滤空记录

elixir - 合并两列并搜索它们

elixir - 分离进程不写入文件 & rpc 调用因连接节点错误而失败

elixir - 我可以将插头放在哪里,然后从 Phoenix 应用程序中的不同 Controller 使用它们?