Setting up test for a plug

I’m attempting to test a plug that requires some request cookies to get set before the test runs. I’ve tried the following:

test "should return true when a sessionID cookie is present", %{conn: conn} do
  Application.put_env(:myapp_interface, :cookie_prefix, "int")
  conn = conn
    |> put_req_cookie("intsessionID", "foobar")
    |> Authorized.call([])

  assert conn.assigns.authorized == true
end

Running that test results in the following error:

** (UndefinedFunctionError) function Plug.Conn.Unfetched.fetch/2 is undefined
  (Plug.Conn.Unfetched does not implement the Access behavior)

I’m stuck trying to figure out what is going on here and what I’ve missed. Can someone either shed some light on what I’m doing wrong or point me to some documentation that shows the proper way to set up this test?

According to the Plug documentation, cookies and other properties of the connection are not fetched until explicitly required:

The request information in these fields is not populated until it is fetched using the associated fetch_ function. For example, the cookies field uses fetch_cookies/2.

So you probably just need to call Plug.Conn.fetch_cookies/2 on your conn in order to make sure the cookies are present.

Thank you so much for the response! That worked beautifully. And thanks for the link to the Plug documentation. I now know a bit more than I did at the start of today!

1 Like