【问题标题】:elixir ecto: test has_many associationelixir ecto:测试 has_many 关联
【发布时间】:2016-05-21 22:18:51
【问题描述】:

我是灵药新手,所以不要太苛刻 我有以下型号:

defmodule MyApp.Device do
  use MyApp.Web, :model

  schema "devices" do
    field :name, :string
    belongs_to :user, MyApp.User

    timestamps
  end
end

defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    field :name, :string
    has_many :devices, MyApp.Device

    timestamps
  end
end

我如何以优雅的方式测试用户拥有许多设备。比如

  test "registration generates user with devices" do
    changeset = Registration.changeset(%Registration{}, @valid_attrs)
    registration = Ecto.Changeset.apply_changes(changeset)
    user = Registration.to_user(changeset)
    IO.puts "#{inspect user}"
    # assert device is inside the user
  end

【问题讨论】:

  • 您引用的 Typi 是什么? Typi.User 和 Typi.Device?我的意思是我猜某个地方有一个 Typi 模块,但它是你的吗?
  • 您可能会发现 Elixir Talk Google Group 的对话内容也值得一读:groups.google.com/forum/#!topic/elixir-ecto/BKpLf092dWs
  • @OnorioCatenacci 已更改为 MyApp :) 忘记重命名内容。我试图隐藏名字
  • @OnorioCatenacci 感谢您的链接,良好的指导方针

标签: unit-testing testing tdd elixir ecto


【解决方案1】:

这样的东西不可行吗?

  test "registration generates user with devices" do
    changeset    = Registration.changeset(%Registration{}, @valid_attrs)
    registration = Ecto.Changeset.apply_changes(changeset)
    user         = Registration.to_user(changeset)
    IO.puts "#{inspect user}"
    # assert device is inside the user
    assert Repo.all(from d in Device, where: d.user_id == ^user.id) != []
  end

【讨论】:

  • 是的,但是 to_user 不会将任何内容保存到 db。所以我只是想测试一下结构
  • 想到的是assert [Map.merge(%MyApp.Device{}, @valid_attrs)] == user.devices,但是它合并了与结构无关的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多