How to test for presence of image asset

I’m having a hard time figuring out how to validate that image assets are being properly served. Here’s a simplified example (ultimately, I want this to work with dynamic assets, but for now trying with a static image):

  test "GET icons", %{conn: conn} do
    conn = get(conn, ~p"/images/Apple_Icon_Logo_one_color@180x180.png")
    assert response_content_type(conn, :file) =~ "image/png"
  done

But this results in a fail:

  1) test GET icons (BossSiteWeb.PageControllerTest)
     test/boss_site_web/controllers/page_controller_test.exs:13
     ** (RuntimeError) expected content-type for file, got: "image/png"
     code: assert response_content_type(conn, :file) =~ "image/png"
     stacktrace:
       (phoenix 1.7.10) lib/phoenix/test/conn_test.ex:319: Phoenix.ConnTest.response_content_type/2
       test/boss_site_web/controllers/page_controller_test.exs:15: (test)

My initial try was with:

assert response_content_type(conn, :"image/png")

That also fails:

     ** (RuntimeError) expected content-type for image/png, got: "image/png"

Having trouble deciphering what I can test for…

The code in response_content_type gives the error message you’re encountering if this function returns false:

Here {part, subpart} will be {"image", "png"}, so you’ll need to pass a format that passes one of the three conditions:

  • matches the result of running MIME.extensions("image/png") - ["png"] on my system
  • is equal to subpart
  • is at the end of the subpart preceded by a +

The third condition doesn’t seem relevant, and the other two are the same. You should pass :png to response_content_type. You may not need the =~ part unless you’re doing something unusual:

assert response_content_type(conn, :png)
1 Like