Action Cable 连接测试用例
单元测试 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
连接自动推断
ActionCable::Connection::TestCase
会从测试类名称自动推断待测连接。如果无法从测试类名称推断出频道,您可以使用 tests
显式设置。
class ConnectionTest < ActionCable::Connection::TestCase
tests ApplicationCable::Connection
end
命名空间
包含的模块