Assert Test Process Did or Will Receive A Message
The ExUnit.Assertions
module contains a function assert_receive which the docs state:
Asserts that a message matching pattern was or is going to be received within the timeout period, specified in milliseconds.
It should possibly in addition say "received by the test process". Let's see if we can send a message from a different process and assert that the test process receives it:
test_process = self()
spawn(fn ->
:timer.sleep(99)
send(test_process, :the_message)
end)
assert_receive(:the_message, 100)
# It Passes!!!
In the above code, :the_message
is sent 1 millisecond before the timeout, and the assertion passes.
Now let's reverse the assertion to refute_receive
, and change the sleep
to the same time as the timeout.
test_process = self()
spawn(fn ->
:timer.sleep(100)
send(test_process, :the_message)
end)
refute_receive(:the_message, 100)
# It Passes!!!
Yep, it passes.
Tweet