Distributed Tests Mix Task

Lately I’ve been working on more distributed applications, and I was struggling to come up with an easy way of testing them with ExUnit. I looked how Phoenix PubSub does theirs and it seemed fairly simple so I pulled it out into a mix task. I figured other people might have a use for this as well so I published it on hex with the name distributed_test.

It’s pretty simple to use, just run mix test.distributed [--count N] and a clustered environment with your app loaded on every node will be started before your tests are ran.

There’s also a helper module in it DistributedEnviroment that has a start/1 and stop/0 function you can use when developing to quickly start up N number of nodes with your application loaded.

There’s a small gotcha with this in that if you define code in your test_helper.exs, it will only be loaded on the master node, so you’ll want to do something like this in your helper file:

defmodule Utils do
  @module (quote do
    defmodule Foo do
      # ...
    end
  end)

  def load_foo() do
    Code.eval_quoted(@module)
    Node.list()
    |> Enum.each(&:rpc.block_call(&1, Code, :eval_quoted, [@module]))
  end
end

and call Utils.load_foo() in your test/in the helper if you need code loaded on all nodes.

9 Likes