Today I Learned

hashrocket A Hashrocket project

Capture IO.puts in ExUnit tests

Whenever writing a CLI you often have to communicate something to the user via IO.puts, and while some languages make it complicated to capture output in a test, Elixir makes it extremely straight-forward.

All we have to do is import the ExUnit.CaptureIO module into our test which exposes the capture_io method.

Example

Implementation:

defmodule MyApp.CLI do
  def main(argv), do
    # parse args ...
    # return :help if the -h switch is supplied
    # pass to process
    argv
    |> parse_args
    |> process
  end
  
  def process(:help) do
    IO.puts "usage: my_app <arg1> <arg2>"
  end
end

IO capturing test:

defmodule CliTest do
  use ExUnit.Case
  
  import ExUnit.CaptureIO
  
  test "prints usage instructions when the help switch is supplied" do
    execute_main = fn ->
      MyApp.CLI.main(["-h"])
    end
    
    assert capture_io(execute_main) =~ "usage:"
  end
end

For more information read the ExUnit.CaptureIO documentation

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.