How to test models with the necessary associations

Using Ecto 2.0:

defmodule PlexServer.BoardInstanceTest do
  use PlexServer.ModelCase

  alias PlexServer.BoardInstance

  @valid_attrs %{board_pieces: [%PlexServer.BoardTileInstance{x: 0, y: 0}], empire: %PlexServer.EmpireInstance{}}
  @invalid_attrs %{}

  test "changeset with valid attributes" do
    changeset = BoardInstance.changeset(%BoardInstance{}, @valid_attrs)
    assert changeset.valid?
  end
end

defmodule PlexServer.BoardInstance do
  use PlexServer.Web, :model

  alias PlexServer.BoardTileInstance

  schema "board_instances" do  
    belongs_to :empire, PlexServer.EmpireInstance
    has_many :board_pieces, BoardTileInstance

    timestamps
  end

  @required_fields ~w()
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
      |> cast(params, @required_fields, @optional_fields)
      |> cast_assoc(:board_pieces, required: true)
      |> cast_assoc(:empire, require: true)
  end
end

My test failed with

** (RuntimeError) related to cast / 3 is not supported, use cast_assoc / 3 instead

The documentation says that cast_assoc / 3 needs to be called after cast / 3, so I'm sure that I am missing something substantial for this test to work.

Edit: updated my code and now got a new error:

** (Ecto.CastError) expected parameters should be a map received: %PlexServer.BoardTileInstance{__meta__: #Ecto.Schema.Metadata<:built>, fleets: #Ecto.Association.NotLoaded<association :fleets is not loaded>, id: nil, inserted_at: nil, system: #Ecto.Association.NotLoaded<association :system is not loaded>, updated_at: nil, x: 0, y: 0}

I assume my @valid_attrs are incorrect, how?

+4
source share
1 answer
  • cast validate_required. @required_fields. cast_assoc , required: true, , . ( , , . 1 .)

  • @valid_attrs , , params Phoenix. cast_assoc . ,

    @valid_attrs %{board_pieces: [%PlexServer.BoardTileInstance{x: 0, y: 0}], empire: %PlexServer.EmpireInstance{}}
    

    @valid_attrs %{board_pieces: [%{x: 0, y: 0}], empire: %{}}
    
+5

All Articles