"cannot load `[]` as type :map for field `products` " when using Repo.preload on tests

I’m running some tests and when I need to use Repo.preload/2 on an User, the test always fail with the error given in the title. I have to say that this works perfectly outside of tests.

My schema:

schema "carts" do
  field(:products, :map)

  belongs_to(:user, User)


And an example failing test:

test "preloading", %{conn: conn, user: user} do
  conn = get(conn, page_path(conn, :index))
  proc = get_session(conn, :proc_id)

  conn =
    |> recycle()
    |> sign_in(user)
    |> get(payments_path(conn, :processed), proc_id: proc)

Once a test hits an endpoint which has to preload an association (which is payments_path(conn, :processed) in this case) it throws that error and honestly I don’t know how to fix it besides changing the type from map to list but that would require to change a lot of the logic in the app.

Can you show the type that your database thinks you are using? If you are using Postgres, you can do the following

$ psql my_database
my_database=# \d+ table_name

Make sure you run that command on your test database and not your production or development database.


Here it is:

                                                         Table "public.carts"
   Column    |            Type             | Collation | Nullable |              Default              | Storage  | Stats target | Description 
 id          | bigint                      |           | not null | nextval('carts_id_seq'::regclass) | plain    |              | 
 user_id     | bigint                      |           | not null |                                   | plain    |              | 
 products    | jsonb[]                     |           |          | ARRAY[]::jsonb[]                  | extended |              | 
 inserted_at | timestamp without time zone |           | not null |                                   | plain    |              | 
 updated_at  | timestamp without time zone |           | not null |                                   | plain    |              | 
    "carts_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "carts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)

EDIT: I see the problem now… I changed the type of the column but I didn’t run the migrations, etc… on the test environment… It’s working now; thank you!

1 Like