- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0 (0)
- 6.1.3.1 (7)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (38)
- 7.1.3.4 (0)
- What's this?
Action Cable Connection TestCase
Unit test Action Cable connections.
Useful to check whether a connection’s identified_by gets assigned properly and that any improper connection requests are rejected.
Basic example
Unit tests are written as follows:
-
Simulate a connection attempt by calling connect.
-
Assert state, e.g. identifiers, has been assigned.
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase def test_connects_with_proper_cookie # Simulate the connection request with a cookie. cookies["user_id"] = users(:john).id connect # Assert the connection identifier matches the fixture. assert_equal users(:john).id, connection.user.id end def test_rejects_connection_without_proper_cookie assert_reject_connection { connect } end end
connect accepts additional information about the HTTP request with the params, headers, session, and Rack env options.
def test_connect_with_headers_and_query_string connect params: { user_id: 1 }, headers: { "X-API-TOKEN" => "secret-my" } assert_equal "1", connection.user.id assert_equal "secret-my", connection.token end def test_connect_with_params connect params: { user_id: 1 } assert_equal "1", connection.user.id end
You can also set up the correct cookies before the connection request:
def test_connect_with_cookies # Plain cookies: cookies["user_id"] = 1 # Or signed/encrypted: # cookies.signed["user_id"] = 1 # cookies.encrypted["user_id"] = 1 connect assert_equal "1", connection.user_id end
Connection is automatically inferred
ActionCable::Connection::TestCase will automatically infer the connection under test from the test class name. If the channel cannot be inferred from the test class name, you can explicitly set it with tests.
class ConnectionTest < ActionCable::Connection::TestCase tests ApplicationCable::Connection end