跳至內容 跳至搜尋

Action Cable Connection TestCase

單元測試 Action Cable 連線。

有助於檢查連線的 identified_by 是否適當地指派,以及任何不當的連線要求是否遭到拒絕。

基本範例

單元測試寫法如下

  1. 透過呼叫 connect 模擬連線嘗試。

  2. 宣告狀態,例如識別碼,已被指派。

    class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase def test_connects_with_proper_cookie # 使用 cookie 模擬連線要求。 cookies = 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 要求的額外資訊,其中包含 paramsheaderssession 和 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

您還可以在連線要求之前設定正確的 cookies

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
命名空間
包含的模組