How to Write Tests

Learn the benefits and the steps needed to follow for writing tests.

We'll cover the following


If there is one thing that every developer probably has an opinion about, it’s testing. We may believe in test-driven development, where we write tests before writing any of our implementation code. Or maybe we follow the practice of code first, test second. We won’t open up any testing philosophy questions in this course. Instead, we’ll look at the available mechanisms for testing our real-time code—and we can apply them using our preferred methodology.

Tests provide us with a higher sense of confidence in our writing code. We can trap complex bugs in robust tests that withstand the test of time. In the ideal world, we can capture any bug in a test and prevent it from happening again in the future.

Phoenix provides a simple and powerful way to write Channel tests. A few basic primitives allow us to quickly write tests of our entire real-time communication stack. We don’t have to worry about the challenges of WebSockets or long polling when we write our tests. Instead, we only have to write tests for the Socket and Channel implementations, which we’ll cover in this section.

Testing Sockets

Every Phoenix application generated with mix includes a few different test helpers found in “test/support.” One of these helpers is called ChannelCase. Ours takes HelloSocketsWeb.ChannelCase. We do not have to worry about customizing this file at this point, since we will not be doing anything out of the ordinary.

Our UserSocket and AuthSocket can connect and identify a Socket. We’ll first write a test for UserSocket because it has no logic. Our tests will assert that we can connect to this Socket. The tests for AuthSocket will be similar but slightly more complex because of the connection logic.

We can run these tests using mix test. It would be best to run that now to verify that our test environment is correctly set up. After we’ve seen that working, let’s move on to writing our UserSocket tests.

Get hands-on with 1000+ tech skills courses.