How to test that a page exists?

One of the default tests checks that a page exists and that the body has a certain string in it:

test "GET /", %{conn: conn} do
    conn = get(conn, ~p"/")
    assert html_response(conn, 200) =~ "Peace of mind from prototype to production"
  end

I’d like to write a similar test that only checks if the page exists (the return status is 200). One way to do this is:

test "GET /page", %{conn: conn} do
    conn = get(conn, ~p"/page")
    assert html_response(conn, 200)
  end

The tests indeed fails if the page doesn’t exist, and passes if it does. However, the reason the test fails is that it raises an error. Which feels like bad practice: to use errors for control flow.

I came up with:

test "GET /page", %{conn: conn} do
    conn = get(conn, ~p"/page")
    assert conn.status == 200
  end

But, I feel like Phoenix should have a more idiomatic way to test this.

What’s the best way to perform this test?

Asserting on the absence of errors in a test is very normal.

2 Likes

One rule:

Unless necessary, avoid testing internal implementations as much as possible.

Let’s set aside the correctness of “use errors for control flow” for now. The code that uses errors for control flow comes from Phoenix, this is not something that application layer code should care about.


Just follow the ultimate goal of testing - “verify that the software operates as expected”.

If what you expected is “the HTML page should be rendered correctly”, then html_response(conn, 200) is enough.

1 Like

The above also raises if the page does not exist, in the first place.

I usually use assert/1 with match to avoid raising, like

assert %Plug.Conn{status: 200} = get(conn, ~p"/page")