Elixir – Testing Phoenix Flash Messages

At times in my integration tests I want to check if a user sees a flash message. It’s easy when re-rendering a template, just check the response body like that:

assert html_response(conn, 200) =~ "some message"

UPD as pointed out by Dave Lugg there is also a built in helper that can do that:

assert get_flash(conn, :info) == “some Message”
assert get_flash(conn, :info) =~ “part of some Message”

But often we set flash messages and redirect the user, in this case response body would not contain them and we’d have to check against the data that is saved on the conn struct, this is doable using Phoenix controller module:

assert(
    conn
    |> Phoenix.Controller.get_flash()
    |> Enum.any?(fn(item) -> String.contains?(elem(item, 1), "some message") end))

which works, but doesn’t look very nice and clutters the tests. So the cleaner solution would be to pack the whole thing in a test helper function and put it in test/support (anything in this directory will be compiled when running tests). Here is an example of such a helper (file test/support/helper.ex):

defmodule MyApp.Helper do
  @moduledoc false

  def flash_messages_contain(conn, text) do
    conn
    |> Phoenix.Controller.get_flash()
    |> Enum.any?(fn(item) -> String.contains?(elem(item, 1), text) end)
  end

end

it can then be used in tests like this:

import MyApp.Helper

...

assert flash_messages_contain(conn, "some message")

2 thoughts on “Elixir – Testing Phoenix Flash Messages

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.