The preferred way to do this is to split your code into clean (without side effects) and unclean (does io). Therefore, if your code looks like this:
IO.gets
...
...
...
IO.gets
...
...
try to extract parts between IO.gets into functions that you can test in isolation from IO.gets:
def fun_to_test do
input1 = IO.gets
fun1(input1)
input2 = IO.gets
fun2(input2)
end
. , , if, case cond.
IO :
def fun_to_test(io \\ IO) do
io.gets
...
...
...
io.gets
...
...
end
, - , fun_to_test(FakeIO). , gets.
defmodule FakeIO do
def gets("prompt1"), do: "value1"
def gets("prompt2"), do: "value2"
end
, , gets:
defmodule FakeIO do
def start_link do
Agent.start_link(fn -> 1 end, name: __MODULE__)
end
def gets(_prompt) do
times_called = Agent.get_and_update(__MODULE__, fn state ->
{state, state + 1}
end)
case times_called do
1 -> "value1"
2 -> "value2"
end
end
end
- . FakeIO.start_link, . , , - , , , . FakeIO , . .