almeynman
almeynman

Reputation: 7418

elixir ecto: test has_many association

I am a newbie in elixir, so don't be too harsh I have following models:

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

How do I test that user has many devices in an elegant way. For instance

  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

Upvotes: 3

Views: 524

Answers (1)

Sasha Fonseca
Sasha Fonseca

Reputation: 2313

Wouldn't something like this work?

  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

Upvotes: 1

Related Questions