Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 759
almeynman Avatar asked Mar 31 '26 10:03

almeynman


1 Answers

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
like image 129
Sasha Fonseca Avatar answered Apr 03 '26 04:04

Sasha Fonseca