Adding Tests to Channels

We started this chapter by testing our information system, including unit-testing our supporting code for the Wolfram backend. Now it’s time to test our channels code. Remember that underneath, channels are also OTP servers. Phoenix includes the Phoenix.ChannelTest module, which will simplify your testing experience. With it, you can make several types of common assertions. For example, you can assert that your application pushes messages to a client, replies to a message, or sends broadcasts. Let’s look at some code.

The rumbl_umbrella/apps/rumbl_web/test/support/channel_case.ex is a file that was generated by Mix when we generated the rumbl application. You’ve already seen a couple of similar test cases with data_case and conn_case in Chapter 8, Testing MVC.

Let’s take a deeper look at how those files work. Crack it open now:

 defmodule​ RumblWeb.ChannelCase ​do
  @moduledoc ​"""
  This module defines the test case to be used by
  channel tests.
 
  Such tests rely on `Phoenix.ChannelTest` and also
  import other functionality to make it easier
  to build common data structures and query the data layer.
 
  Finally, if the test case interacts with the database,
  it cannot be async. For this reason, every test runs
  inside a transaction which is reset at the beginning
  of the test unless the test case is marked as async.
  """
 
 use​ ExUnit.CaseTemplate
 
  using ​do
 quote​ ​do
 # Import conveniences for testing with channels
 use​ Phoenix.ChannelTest
 
 # The default endpoint for testing
  @endpoint RumblWeb.Endpoint
 end
 end
  setup tags ​do
 :ok​ = Ecto.Adapters.SQL.Sandbox.checkout(Rumbl.Repo)
 
 unless​ tags[​:async​] ​do
  Ecto.Adapters.SQL.Sandbox.mode(Rumbl.Repo, {​:shared​, self()})
 end
 
 :ok
 end
 end

Knowing what’s happening here in basic broad strokes is enough. First you see use ExUnit.CaseTemplate, which establishes this file as a test case. Next is a using block to start an inline macro, and a quote to specify the template for the code that we want to inject. The use Phoenix.ChannelTest statement establishes Phoenix.ChannelTest as the foundation for our test file. Then, we do a few imports and aliases for convenience, and so on.

The result is a file that prepares your tests for the features you’re most likely to use in your channel tests. Our application has just one channel: the VideoChannel, which supports features like real-time annotations and integration with our InfoSys layer. All of our tests go through a single endpoint.

Before we test the VideoChannel, let’s start where the channel process begins by testing the UserSocket module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83