Skip to content

Instantly share code, notes, and snippets.

@joeyates
Created December 26, 2016 20:26
Show Gist options
  • Select an option

  • Save joeyates/c5575c5506e465a419d770c61d7eacb2 to your computer and use it in GitHub Desktop.

Select an option

Save joeyates/c5575c5506e465a419d770c61d7eacb2 to your computer and use it in GitHub Desktop.
(In tests) how to capture another process's IO
defmodule GenServerThatUsesStdio do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, [])
end
def handle_cast(message, state) do
IO.puts message
{:noreply, state}
end
end
defmodule SetProcessesGroupLeaderTest do
use ExUnit.Case
test "capturing another process's output on stdio" do
{:ok, pid} = GenServerThatUsesStdio.start_link()
{:ok, capture_gl} = StringIO.open("")
Process.group_leader(pid, capture_gl)
GenServer.cast pid, 42
# Give the process time to handle the cast before it gets killed!
:timer.sleep 100
{:ok, {_, output}} = StringIO.close(capture_gl)
assert output == "42\n"
Process.exit(pid, :normal)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment