Testing recursive IO prompt

Hello everyone!

I have a function confirm, which reads IO input, and depending by input, if it’s “y” (yes) or “n” (no), it returns true/false, otherwise it calls confirm again, until any expected “y” or “n” is entered.

@spec confirm(binary) :: boolean
def confirm(question) do
  answer = question |> IO.gets() |> String.trim() |> String.downcase()

  case(answer) do
    "y" -> true
    "n" -> false
    _ -> confirm(question)
  end
end

To test “y” and “n” cases it’s easy:

assert capture_io([input: "y"], fn -> confirm("Question") end) == "Question"

But I have no idea how to capture IO multiple times to test recursive case, let’s say if at first input is “invalid” and then “y”. Does elixir has any way to test IO functions like this? Or maybe do you have some suggestions how I could rewrite function to test it easier? Thanks for the help.

3 Likes

Solution: http://stackoverflow.com/questions/42280760/testing-recursive-io-prompt-in-elixir-erlang

5 Likes