Ricardo Valeriano
Ricardo Valeriano

Reputation: 7793

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

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

Upvotes: 3

Views: 453

Answers (1)

Dogbert
Dogbert

Reputation: 222188

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

Upvotes: 5

Related Questions