Is there a way to test an IO output using Doctest in Elixir?

436 Views Asked by At

I'm totally ok with writing a "normal" test capturing the IO for this.

Would just like to know if it is possible to use Doctest.

An example would be:

defmodule CLI do

  @doc """
  Politely says Hello.

  ## Examples

      iex> CLI.main([])
      "Hello dear person." # this would be the expected IO output
  """
  def main(args) do
    IO.puts "Hello dear person."
  end
end

defmodule CLITest do
  use ExUnit.Case
  doctest CLI
end
1

There are 1 best solutions below

1
On BEST ANSWER

You can use the same function as you'd use in a normal test: ExUnit.CaptureIO.capture_io. This might not be a function suited for doctests though when you add more functionality to the function.

defmodule CLI do
  @doc """
  Politely says Hello.

  ## Examples

      iex> import ExUnit.CaptureIO
      iex> capture_io(fn -> CLI.main([]) end)
      "Hello dear person.\\n"
  """
  def main(args) do
    IO.puts "Hello dear person."
  end
end
$ mix test
.

Finished in 0.03 seconds
1 test, 0 failures