biagidp
biagidp

Reputation: 2185

Assert pattern match in phoenix tests

I'm testing a phoenix/elixir application, and I find myself using something like the following an awful lot.

player = insert(:player)
assert [%Player{id: x}] = Players.site_players(player.site_id)
assert x == player.id

This accomplishes the things I want, mainly it ensures that Players.site_players/1 returns an array and that array includes the player. I feel like this could be done more concisely. Any suggestions?

Upvotes: 0

Views: 866

Answers (1)

Dogbert
Dogbert

Reputation: 222148

I'm not sure how concise you were expecting, but here's how to do the same thing in one less line of code:

%Player{id: id, site_id: site_id} = insert(:player)
assert [%Player{id: ^id}] = Players.site_players(site_id)

As you may already know, you cannot have a function call along with the pin operator, only a local variable name, which is why we extract the id into a variable in the first line.

The first line can also be the following if you want:

%{id: id, site_id: site_id} = insert(:player)

Upvotes: 1

Related Questions