Search code examples
elixirstdoutex-unit

How can I test a multiline output in Elixir?


How can I test the following code?

["one", "two", "three"]) |> Enum.each(&IO.puts(&1))
one
two
three
:ok

My test currently looks like this, but is failing because IO.puts returns :ok rather that the strings, and probably does not include newline characters in a complete string.

assert ["one", "two", "three"]) |> Enum.each(&IO.puts(&1)) == """
one
two
three
"""

Perhaps IO.puts is the wrong function for this use case. If so, what alternative might I use?

Thanks in advance.


Solution

  • Use capture_io.

    fun = fn -> ["one", "two", "three"] |> Enum.each(&IO.puts/1) end
    assert capture_io(fun) == "one\ntwo\nthree\n"