Rails所針對的是Web項目,必須要考慮大訪問量的情況,所以我們來看看在Rails怎樣進行效能測試。
1.要進行效能測試,我們首先要模仿大量的資料,我們現在知道,在test/fixtures/目錄下的yml檔案裡添加我們的測試資料,在運行測試時,這些資料會被載入到資料庫。但是一條兩條資料還可以,資料多的情況下,一條一條在yml檔案裡寫可不行,所以,我們先看看怎樣在yml檔案裡造大量的資料。在fixtrue目錄下建立一個子目錄performance,在裡面建立order.yml檔案,把內容改成下面的樣子:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html<% for i in 1..100 %>order_<%= i %>: id: <%= i %> name: Fred email: fred@flintstones.com address: 123 Rockpile Circle pay_type: check<% end %>
然後再運行我們一個空測試,order_test.rb
depot>ruby test/unit/order_test.rb
到資料庫裡查看下錶order,裡面已經初始化了100條記錄了。我們之所以要建立一個performance目錄,是因為我們不想運行每個測試都要初始化100條記錄,我們之前在測試model和controller的時候用的那個order.yml檔案中的記錄就夠了。
2.在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 elapsedSeconds = 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 assert elapsedSeconds < 3.0, "Actually took #{elapsedSeconds} seconds" endend