Today I Learned

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.



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

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 ->
    assert capture_io(execute_main) =~ "usage:"

For more information read the ExUnit.CaptureIO documentation

Looking for help? Elixir is quickly gaining momentum for web applications that need concurrency, performance, and the ability to connect to many different clients. The developers at Hashrocket are learning along with the rest of the development community that Elixir and Phoenix are viable Rails alternatives for the right application. Check out the source code for Today I Learned, written in Elixir, and contact us if you need help with your Elixir project.