Avoiding message leaks in tests?

Hi!

When using assert_receive, how do you avoid leaking messages between tests?

Let’s assume that Test.publish(1) just sends the 1 to the test process (self()).

    test "do something" do
      result = Test.publish(1)

      assert result == :ok
    end

    test "do something else" do
      # We forgot to publish 
      # Test.publish(1)

      assert_receive 1 # This would succeed randomly
    end

The second test here would succeed randomly, if it’s being run after the first test.

How do you avoid this? Just adding a function to clear the mailbox between each test?

I can’t seem to replicate this behavior. Granted, it is not the same codebase as yours :grinning: Does assert_received/2 give you the same result?

1 Like

Each test runs in a separate process, so it is not possible for messages to leak, unless the “leaked” message is coming from your setup block, which is run on every test.

3 Likes

Yeah, there’s definitely something weird going on in my code. When running a simpler test it doesn’t actually leak anything.

Probably some external thing!

Thanks!