Assert_broadcast unexpected behaviour

Hello everyone,
I’m moving my first steps with Elixir/Phoenix, it’s great and also the community is very wide, congrats!
I’m writing my first post in this forum because I’ve encoutered a strange behaviour and didn’t found any explanation in doc.

While testing channels, when I assert if a message has been broadcasted to the channels (among which there is the channel I subscribed to), all is fine when in assert_broadcast macro I pass, for example, a map as payload (example taken from doc):

assert_broadcast "some_event", %{"data" => "foo"}

But if I pass a variable as payload, the test always pass also if the variable is different to the expected payload! For example:

var1 = %{"data" => "foo"}
var2 = %{"data" => "bar"}

# This passes
assert_broadcast "some_event", %{"data" => "foo"}

# This also passes
assert_broadcast "some_event", var1

# But this also passes, and it shouldn't!
assert_broadcast "some_event", var2

Why this?

because assert_broadcast matches by pattern. For your use case you have to use ^ pin operator

assert_broadcast "some_event", ^var1
assert_broadcast "some_event", ^var2

otherwise, the value of sent message will be assigned to var1 or var2

2 Likes

Clear! It was so simple, but I have still to understand well how ^ works :slight_smile:

Thanks a lot!