ExUnit.CaptureIO

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
end
Source

Summary

capture_io(fun)

Captures IO generated when evaluating fun

capture_io(device, fun)
capture_io(device, input, fun)

Functions

capture_io(fun)

Captures IO generated when evaluating fun.

Returns nil in case of no output, otherwise 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.

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 "josé" end) == "josé"
true
iex> capture_io(:stderr, fn -> IO.write(:stderr, "josé") end) == "josé"
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
Source
capture_io(device, fun)
Source
capture_io(device, input, fun)
Source