elixir ecto:test has_many association

时间:2016-05-20 15:56:12

标签: unit-testing testing tdd elixir ecto

我是长生不老药的新手,所以不要太苛刻 我有以下模型:

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

1 个答案:

答案 0 :(得分: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