We'll need to fix up our tests very quickly as well. For the most part, we can just reuse the code from the poll channel tests. We'll start off with a standard channel test skeleton. Create test/vocial_web/channels/chat_channel_test.exs and we'll start it off simply enough:
defmodule VocialWeb.ChatChannelTest do
use VocialWeb.ChannelCase
alias VocialWeb.ChatChannel
end
Next, we'll add a setup block. We'll start off by creating a user and a poll to give us our baseline:
setup do
{:ok, user} = Vocial.Accounts.create_user(%{
username: "test",
email: "[email protected]",
password: "test",
password_confirmation: "test"
})
{:ok, poll} = Vocial.Votes.create_poll_with_options(
%{ "title" => "My New Test Poll", "user_id" => user.id },
["One", "Two", "Three"]
)
Then we'll create a mock socket that will join the chat lobby and the chat for the created poll:
socket = socket("user_id", %{user_id: user.id})
{:ok, _, poll_socket} = subscribe_and_join(socket, ChatChannel, "chat:#{poll.id}", %{})
{:ok, _, lobby_socket} = subscribe_and_join(socket, ChatChannel, "chat:lobby", %{})
Finally, we return out the information that we've created as a part of this setup block:
{:ok, poll_socket: poll_socket, lobby_socket: lobby_socket, user: user, poll: poll}
end
Next, we'll write a test that makes sure we get a reply from the socket and a broadcast from the socket that matches the author/message format we specified in the channel itself:
test "new_message replies with status ok for chat:poll_id", %{poll_socket: socket} do
ref = push socket, "new_message", %{"author" => "test", "message" => "Hello World"}
assert_reply ref, :ok, %{author: author, message: message}
assert author == "test"
assert message == "Hello World"
assert_broadcast "new_message", %{author: author, message: message}
assert author == "test"
assert message == "Hello World"
end
Finally, we duplicate the test for the chat lobbies as well:
test "new_message replies with status ok for chat:lobby", %{lobby_socket: socket} do
ref = push socket, "new_message", %{"author" => "test", "message" => "Hello World"}
assert_reply ref, :ok, %{author: author, message: message}
assert author == "test"
assert message == "Hello World"
assert_broadcast "new_message", %{author: author, message: message}
assert author == "test"
assert message == "Hello World"
end
And that's it! If we run our tests for the chat channel now, we should see nice green tests:
mix test test/vocial_web/channels/chat_channel_test.exs
..
Finished in 1.2 seconds
2 tests, 0 failures
Randomized with seed 933948