【发布时间】:2015-11-26 00:33:52
【问题描述】:
我正在尝试测试 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
要测试这种关联,您基本上可以放弃强制转换和验证。
【问题讨论】:
标签: elixir phoenix-framework ecto