2

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.

FelixFortis
  • 684
  • 6
  • 16

1 Answers1

5

Use capture_io.

fun = fn -> ["one", "two", "three"] |> Enum.each(&IO.puts/1) end
assert capture_io(fun) == "one\ntwo\nthree\n"
wadie
  • 496
  • 1
  • 10
  • 24
Martin Svalin
  • 2,227
  • 1
  • 17
  • 23
  • Thanks for the great answer. Is there a way that doctest can handle leading whitespace? " my_string " – FelixFortis Nov 02 '16 at 06:42
  • Sorry about the confusion, I looked it up and doctest does not (any longer?) support capturing io. I edited my answer, as the part about doctest was wrong. – Martin Svalin Nov 02 '16 at 13:07