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

Ruby on Rails 開發從頭來(二十九):效能測試實戰指南

     編輯:Java 相關知識

效能測試三步驟

  1. 準備大量測試資料
  2. 撰寫效能測試案例
  3. 使用分析工具定位瓶頸

大量測試資料產生

在 test/fixtures/performance/orders.yml 使用 ERB 迴圈產生 100 筆訂單:

<% for i in 1..100 %>
order_<%= i %>:
  id: <%= i %>
  name: Fred
  email: fred@flintstones.com
  address: 123 Rockpile Circle
  pay_type: check
<% end %>

執行 ruby test/unit/order_test.rb 即可載入資料庫驗證。

效能測試案例撰寫

在 test/performance/order_test.rb:

require File.dirname(__FILE__) + '/../test_helper'
require 'store_controller'

class OrderTest < Test::Unit::TestCase
  fixtures :products
  HOW_MANY = 100

  def setup
    @controller = StoreController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    get :add_to_cart, :id => 1  # 確保購物車有商品
  end

  def teardown
    Order.delete_all
  end

  def test_save_bulk_orders
    elapsed = Benchmark::realtime do
      # 載入大量測試資料
      Fixtures.create_fixtures(File.dirname(__FILE__) + "/../fixtures/performance", "orders")
      assert_equal HOW_MANY, Order.find(:all).size

      # 逐筆下單並驗證
      1.upto(HOW_MANY) do |id|
        order = Order.find(id)
        get :save_order, :order => order.attributes
        assert_redirected_to :action => 'index'
        assert_equal "Thank you for your order.", flash[:notice]
      end
    end
    # 斷言:100 筆訂單處理需在 3 秒內完成
    assert elapsed < 3.0, "Actually took #{elapsed} seconds"
  end
end

關鍵點

  • 使用 Benchmark::realtime 精確測量執行時間
  • Fixtures.create_fixtures 動態載入指定目錄 fixtures
  • teardown 清理資料,避免測試間相互干擾
  • 測試真實流程:找訂單 → 呼叫 Action → 驗證導向與 Flash

控制 Fixtures 載入行為

class OrderTest < Test::Unit::TestCase
  self.use_transactional_fixtures = true  # 使用交易回滾,加速測試
  fixtures :products
  # ...
end

開啟後,每個測試方法在交易中執行,結束自動回滾,無需手動 delete_all。

程式碼層級效能分析工具

Profiler:單一方法熱點分析

ruby script/performance/profiler "Product.salable_items"

輸出各方法呼叫次數、耗時、佔比,快速找出熱點方法。

Benchmarker:多方法比較

ruby script/performance/benchmarker 10 "Product.salable_items" "Order.count_pending"

執行 10 次迴圈,比較兩方法平均耗時:

user     system      total        real
#1  0.078000   0.000000   0.078000 (  0.078000)
#2  0.000000   0.000000   0.000000 (  0.016000)

參數順序:迴圈次數 "方法1" "方法2" ...,方法間以空格分隔。

持續效能監控建議

  • 將效能測試納入持續整合流程(如 Jenkins),每日自動執行並追蹤趨勢。
  • 設定效能基準門檻,超標自動通知開發團隊。
  • 針對關鍵 API(結帳、搜尋、報表)建立專門效能測試套件。
  • 結合 New Relic、Skylight 等 APM 工具監控生產環境真實效能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved