Can I do a test of Repo.get?

I want to check if my schema works properly.

This is my test code.

defmodule DbServerWeb.GameSchemaTest do
  use ExUnit.Case, async: true
  use DbServer.DataCase

  alias DbServer.Games
  alias DbServer.Schema.Game

describe "select from game table." do
    @insert_params %{game_name: "test_name"}
    @valid_params %{id: 0}

    test "get a row from a table with a valid data." do
      _ = Games.create_game(@insert_params)
      assert {%Game{} = game} = Games.get_game(@valid_params)
    end
  end
end

And this is my tested code.

defmodule DbServer.Games do
  @moduledoc """
    The games context.
  """
  import Ecto.Query, warn: false
  
  alias DbServer.Repo
  alias DbServer.Schema.Game

  def get_game(params \\ %{}) do
    case params do
      %{id: id} ->
        Repo.get!(Game, id)
    end
  end
end

But then, my terminal says

..

  1) test select from game table. get a row from a table with a valid data. (DbServerWeb.GameSchemaTest)
     test/db_server_web/schema/game_schema_test.exs:26
     ** (Ecto.NoResultsError) expected at least one result but got none in query:
     
     from g0 in DbServer.Schema.Game,
       where: g0.id == ^0
     
     code: assert {%Game{} = game} = Games.get_game(@valid_params)
     stacktrace:
       (ecto) lib/ecto/repo/queryable.ex:107: Ecto.Repo.Queryable.one!/3
       test/db_server_web/schema/game_schema_test.exs:28: (test)

.

How can I get the result?

You assume the Game has an id equal to 0. Newly created games will probably have a different id.

Presumably when you create the game with Games.create_game(@insert_params), the newly created game is returned. You should use the id of this returned game and use this in Games.get_game/1

5 Likes

Just in case, %Game{…} != {%Game{…}} as second one is unary tuple (which is pretty pointless, but possible).

1 Like

Thanks!
It helped me! <3

1 Like

My all CRUD tests worked!

Thank you!

defmodule DbServerWeb.GameSchemaTest do
  use ExUnit.Case, async: true
  use DbServer.DataCase

  alias DbServer.Games
  alias DbServer.Schema.Game

  describe "game schema test." do
    @insert_params %{game_name: "test_name"}

    test "crud test." do
      assert {_, struct} = Games.create_game(@insert_params)
      assert %Game{} = game = Games.get_game(struct.id)
      assert {:ok, %Game{} = game} = Games.update_game(game, %{:game_name => "updated_one"})
      assert {:ok, %Game{} = game} = Games.delete_game(game)
    end
  end
end