ExUnit.CaptureIO View Source
Functionality to capture IO for testing.
Examples
defmodule AssertionTest do
use ExUnit.Case
import ExUnit.CaptureIO
test "example" do
assert capture_io(fn ->
IO.puts "a"
end) == "a\n"
end
test "checking the return value and the IO output" do
fun = fn ->
assert Enum.each(["some", "example"], &(IO.puts &1)) == :ok
end
assert capture_io(fun) == "some\nexample\n"
# tip: or use only: "capture_io(fun)" to silence the IO output (so only assert the return value)
end
end
Link to this section Summary
Functions
Captures IO generated when evaluating fun
Link to this section Functions
capture_io(fun) View Source
Captures IO generated when evaluating fun
.
Returns the binary which is the captured output.
By default, capture_io
replaces the group_leader
(:stdio
)
for the current process. However, the capturing of any other
named device, such as :stderr
, is also possible globally by
giving the registered device name explicitly as an argument.
Note that when capturing something other than :stdio
,
the test should run with async: false
.
When capturing :stdio
, if the :capture_prompt
option is false
,
prompts (specified as arguments to IO.get*
functions) are not
captured.
A developer can set a string as an input. The default input is :eof
.
Examples
iex> capture_io(fn -> IO.write("john") end) == "john"
true
iex> capture_io(:stderr, fn -> IO.write(:stderr, "john") end) == "john"
true
iex> capture_io("this is input", fn ->
...> input = IO.gets ">"
...> IO.write input
...> end) == ">this is input"
true
iex> capture_io([input: "this is input", capture_prompt: false], fn ->
...> input = IO.gets ">"
...> IO.write input
...> end) == "this is input"
true
Returning values
As seen in the examples above, capture_io
returns the captured output.
If you want to also capture the result of the function executed inside
the capture_io
, you can use Kernel.send/2
to send yourself a message
and use ExUnit.Assertions.assert_received/2
to match on the results:
capture_io([input: "this is input", capture_prompt: false], fn ->
send self(), {:block_result, 42}
# ...
end)
assert_received {:block_result, 42}