Action Cable Connection TestCase¶ ↑
单元测试 Action Cable 连接。
这对于检查连接的 identified_by 是否正确分配以及任何不当的连接请求是否被拒绝非常有用。
基本示例¶ ↑
单元测试通过首先调用 connect 来模拟连接尝试,然后断言状态(例如,标识符)已被分配来编写。
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 接受有关 HTTP 请求的附加信息,通过 params、headers、session 和 Rack env 选项。
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
您还可以在连接请求之前设置正确的 cookie
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 会被自动推断¶ ↑
ActionCable::Connection::TestCase 会自动从测试类名中推断出正在测试的连接。如果无法从测试类名中推断出通道,则可以使用 tests 显式设置它。
class ConnectionTest < ActionCable::Connection::TestCase tests ApplicationCable::Connection end
命名空间
包含的模块