Background
I have a some tests that create a worker and wait for said worker to open a connection. To test if the connection is up I pass along some stubs in the workers start_link
. I check the the stubs were executed using counters
.
Problem
All is fine but only some times. Sometimes my test suite passes, other times it fails. And this is random, which is really annoying.
Following is a test sample:
test "saves base_url to dumper and metrics if it cannot connect to it" do
Process.flag :trap_exit, true
dumper = :counters.new(1, [])
metrics = :counters.new(1, [])
args = %{
deps: %{
dumper: %{
save_failed_request: fn _url ->
:counters.add(dumper, 1, 1)
{:ok, :saved}
end
},
metrics: %{
inc: fn _id ->
:counters.add(metrics, 1, 1)
{:ok, 1}
end
}
}
}
{:ok, _pid} = Worker.start_link(args)
dumper_calls = :counters.get(dumper, 1)
dumper_expected_calls = 1
metrics_calls = :counters.get(dumper, 1)
metrics_expected_calls = 1
assert dumper_calls === dumper_expected_calls
assert metrics_calls === metrics_expected_calls
assert_receive {:EXIT, _, :timeout}, 600
Process.flag :trap_exit, false
end
I guess I could extend the assert_receive
to long times, but then my test suite would be painfully slow.
I assume this is happening because the Worker
dies before sending messages or the test somehow finishes without waiting for my worker.
Is there is simple way to fix this so my tests pass consistently ?