ExUnit v1.4.5 ExUnit.CaptureIO View Source

Functionality to capture IO for testing.


defmodule AssertionTest do
  use ExUnit.Case

  import ExUnit.CaptureIO

  test "example" do
    assert capture_io(fn ->
      IO.puts "a"
    end) == "a\n"

  test "checking the return value and the IO output" do
    fun = fn ->
      assert Enum.each(["some", "example"], &(IO.puts &1)) == :ok
    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)

Link to this section Summary

Link to this section Functions

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.


iex> capture_io(fn -> IO.write "john" end) == "john"

iex> capture_io(:stderr, fn -> IO.write(:stderr, "john") end) == "john"

iex> capture_io("this is input", fn ->
...>   input = IO.gets ">"
...>   IO.write input
...> end) == ">this is input"

iex> capture_io([input: "this is input", capture_prompt: false], fn ->
...>   input = IO.gets ">"
...>   IO.write input
...> end) == "this is input"

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}
  # ...

assert_received {:block_result, 42}
Link to this function capture_io(device, input, fun) View Source