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
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 documentationTweet