Home Posts Tags Post Search Tag Search

Post 19

Game Site Journal - 11 Tests

Published on: 2025-04-21 Tags: elixir, Blog, Side Project, Testing, LiveView, Game Site, Deployment, Html/CSS
So for this one I wanted to go over what I had to do to test some things for the Games that I created.

First and foremost I needed to set the setup for the series of tests.

describe "Guessing" do
    setup do
      user = user_fixture()
      game = game_fixture(%{game_id: 1})

      %{user: user, game: game}
    end

This sets the initial state for the rest of the tests. What ever you end the setup with is what you can pass to the individual tests.

Once that was done we need to be sure to add %{conn: conn, user: user}
test "test", %{conn: conn, user: user} do
....
end

Now that we have the intitial state in every test we need to be sure to log in the user, and then visit the route for the game we want to test
conn =
        conn
        |> log_in_user(user)

      {:ok, view, html} = live(conn, ~p"/1")

You might notice 2 things html and view

html is the rendered html for the page
view (often called lv or live_view in tests) is your handle to the running LiveView process

with these to 2 things you can: 
test any value that you might have in the rendered page
or get the values for the current state of the page

to get the values for the page you must retrieve the socket from the view, I created a private function for this.

defp get_socket(view) do
      state = :sys.get_state(view.pid)
      state.socket
    end

So for any test that I need to know the random value, ie answer in this case I can get that and test a "good answer"

Ill show you a full test for a good answer below

test "good guess", %{conn: conn, user: user} do
      conn =
        conn
        |> log_in_user(user)

      {:ok, view, _html} = live(conn, ~p"/1")

      socket = get_socket(view)
      answer = socket.assigns.answer

      {:noreply, new_socket} =
        GameSiteWeb.GuessingLive.handle_event(
          "answer",
          %{"guess" => to_string(answer), "wager" => "2"},
          socket
        )

      assert new_socket.assigns.attempt == 1
      assert new_socket.assigns.wager == 2
      assert new_socket.assigns.score == 12
      assert Phoenix.Flash.get(new_socket.assigns.flash, :info) == "Correct!"
    end

I hope this helps with making good test cases for the code you will build.