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.

1 Answer 1

5

Use capture_io.

fun = fn -> ["one", "two", "three"] |> Enum.each(&IO.puts/1) end
assert capture_io(fun) == "one\ntwo\nthree\n"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the great answer. Is there a way that doctest can handle leading whitespace? " my_string "
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.