首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發從頭來(二十四):控制器測試入門 (StoreController)

     編輯:Java 相關知識

功能測試基礎設施

Rails 產生控制器時自動建立 test/functional/<controller>_controller_test.rb,預載入三大核心物件:

def setup
  @controller = StoreController.new
  @request    = ActionController::TestRequest.new
  @response   = ActionController::TestResponse.new
end

無需啟動 Web 伺服器,直接在記憶體中模擬 HTTP 請求/回應週期。

測試首頁動作

def test_index
  get :index
  assert_response :success
  assert_equal 2, assigns(:products).size  # fixtures 載入 2 本書
  assert_template "store/index"
end

關鍵斷言

  • get :index:模擬 GET 請求
  • assert_response :success:HTTP 200 OK
  • assigns(:products):取得控制器實例變數 @products
  • assert_template:驗證渲染模板

測試加入購物車

def test_add_to_cart
  @product = Product.find(1)  # 取代失效的 @version_control_book
  get :add_to_cart, :id => @product.id
  
  cart = session[:cart]
  assert_equal @product.price, cart.total_price
  assert_redirected_to :action => 'display_cart'
  
  follow_redirect  # 關鍵:模擬瀏覽器跟隨導向
  assert_equal 1, assigns(:items).size
  assert_template "store/display_cart"
end

follow_redirect 重要性

導向後,assigns 與 assert_template 針對目標動作(display_cart)而非來源動作(add_to_cart),確保驗證正確視圖。

測試無效商品 ID

def test_add_to_cart_invalid_product
  get :add_to_cart, :id => '-1'
  assert_redirected_to :action => 'index'
  assert_equal "Invalid product", flash[:notice]
end

控制器應處理 ActiveRecord::RecordNotFound 並設定友善提示。

測試與模型測試的分工

  • 模型測試:驗證業務規則、關聯、驗證、回呼、資料庫操作
  • 控制器測試:驗證 HTTP 回應、導向、模板渲染、Session/Flash 操作、參數處理
  • 若控制器測試失敗但模型測試通過 → 問題在控制器邏輯
  • 若兩者皆失敗 → 優先檢查模型層

測試資料清理

def teardown
  LineItem.delete_all  # 測試未使用 line_item fixtures,手動清理
end

避免測試間資料污染,確保獨立性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved