gintko
gintko

Reputation: 697

Testing recursive IO prompt in Elixir/Erlang

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?

Original question https://elixirforum.com/t/testing-recursive-io-prompt/3715

Thanks for the help.

Upvotes: 3

Views: 329

Answers (1)

marco.m
marco.m

Reputation: 4859

Untested, but what about just using newline characters?

assert capture_io([input: "foo\nbar\ny"], fn -> confirm("Question") end) == "Question"

Upvotes: 4

Related Questions