Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a mailbox in channelcase phoenix framework test

I am doing a channel test that is receiving lots of messages. I may receive a message during setup, adjust some state and then I want to assert ( or refute ) another copy of that message was sent. I think I could do this by clearing the mailbox before causing the event which would trigger the second message. How do I clear the channelcase mailbox?

EDIT, I have accomplished my needs by assert_push all of the old messages, which clears them off of the mailbox. This works well enough but would be very inconvenient if there were more than a few messages

like image 956
crododile Avatar asked Oct 19 '16 19:10

crododile


3 Answers

Just to clarify if anyone likes me gets quite confused with this problem.

The messages sent through the channel are stored at the test process mailbox, so in order to clean the messages we just need to clean the mailbox of the process. So using what Mark posted above we can flush the messages.

P.D: Using this :erlang.process_info(self(), :messages) |> IO.inspect() we can see the current messages at the process mailbox.

like image 175
jkmrto Avatar answered Nov 19 '22 19:11

jkmrto


Edit: :lib.flush_receive() works perfectly! Unfortunately it looks like the module has been deprecated and I can't find a replacement.

I've been searching for a solution to this. assert_push isn't practical for me as there are many messages that are queued and not relevant to my test. You can use :c.flush() which dumps all the messages. Unfortunately I don't yet know how to prevent this from printing it out to the console.

like image 27
Alejandro Huerta Avatar answered Nov 19 '22 21:11

Alejandro Huerta


An easy way to accomplish this is to simply receive the %Phoenix.Socket.Message{}.

For example:

def flush_messages(timeout \\ 100) do
  receive do
    %Phoenix.Socket.Message{} ->
      flush_messages()
  after
    timeout -> nil
  end
end

The timeout is there to allow pending messages to arrive. 100m is also the default timeout for assert_receive, which is being used by assert_push.

like image 1
Mark Meeus Avatar answered Nov 19 '22 19:11

Mark Meeus