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 OKassigns(:products):取得控制器實例變數 @productsassert_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
導向後,assigns 與 assert_template 針對目標動作(display_cart)而非來源動作(add_to_cart),確保驗證正確視圖。
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 並設定友善提示。
def teardown
LineItem.delete_all # 測試未使用 line_item fixtures,手動清理
end
避免測試間資料污染,確保獨立性。