跳到內容 跳到搜尋

Action Controller 測試案例

ActionController 功能測試的超類別。功能測試讓您在每個測試方法中測試單一控制器動作。

使用整合樣式控制器測試,而非功能樣式控制器測試。

Rails 鼓勵使用整合測試,而非功能測試(使用 ActionDispatch::IntegrationTest)。

新的 Rails 應用程式不再產生功能樣式控制器測試,且它們僅用來進行向後相容性。整合樣式控制器測試會執行實際要求,而功能樣式控制器測試則只是模擬要求。此外,整合測試與功能測試一樣快,並提供許多協助工具(例如 asparsed_body,以便對控制器動作進行有效測試,甚至包括 API 端點。

基本範例

功能測試的撰寫如下:1. 首先,使用 getpostpatchputdeletehead 方法模擬 HTTP 要求。2. 然後,宣告目前的狀態是否如預期。「狀態」可以是任何項目:控制器的 HTTP 回應、資料庫內容等等。

例如

class BooksControllerTest < ActionController::TestCase
  def test_create
    # Simulate a POST response with the given HTTP parameters.
    post(:create, params: { book: { title: "Love Hina" }})

    # Asserts that the controller tried to redirect us to
    # the created book's URI.
    assert_response :found

    # Asserts that the controller really put the book in the database.
    assert_not_nil Book.find_by(title: "Love Hina")
  end
end

您也可以在模擬的 HTTP 要求中傳送真實文件。

def test_create
  json = {book: { title: "Love Hina" }}.to_json
  post :create, body: json
end

特別執行個體變數

ActionController::TestCase 也會自動提供下列執行個體變數供測試使用

@controller

即將測試的控制器執行個體。

@request

ActionController::TestRequest,代表目前 HTTP 要求。您可以在傳送 HTTP 要求前修改此物件。例如,您可能想要在傳送 GET 要求前設定一些階段屬性。

@response

ActionDispatch::TestResponse 物件,代表上一個 HTTP 回應的回應。在上方的範例中,@response 在呼叫 post 之後會變為有效。如果各個宣告方法不足,那麼您可以使用此物件詳查 HTTP 回應。

自動推斷控制器

ActionController::TestCase 會自動從測試類別名稱推斷受測控制器。如果無法從測試類別名稱推斷控制器,您可以在 tests 中明確地設定它。

class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
  tests WidgetController
end

Testing 控制器的內部

除了這些特定的宣告語彙之外,您也可以輕鬆使用各種集合,並對其使用一般的測試/單元宣告語彙。這些集合為

  • session:儲存在階段中的物件。

  • flash:目前在階段中的快訊物件。

  • cookies:此要求會傳送給使用者,作為 Cookies

這些集合可視為其他雜湊一樣使用

assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
assert flash.empty? # makes sure that there's nothing in the flash

在集合的上方,包含給定動作重新導向至的完整 URL,可在 redirect_to_url 中取得。

在同一個控制器中重新導向時,甚至可以呼叫 follow_redirect ,重新導向將會處理,並會觸發另外一個動作呼叫,然後可以針對其進行斷言。

操控 session 和 cookie 變數

有時候需要為測試設定 session 和 cookie 變數,這樣做只需為 session 或 cookie 集合指定一個值即可

session[:key] = "value"
cookies[:key] = "value"

要清除測試的 cookie,只需清除 cookie 集合

cookies.clear

Testing 命名路徑

如果您使用命名路徑,可以透過在測試個案中直接使用原始命名路徑的方法輕鬆地測試它們。

assert_redirected_to page_url(title: 'foo')
名稱空間
已包含的模組

屬性

[RW] executor_around_each_request