Ruby on rails开发从头来(windows)(二十九)- 性能测试2011-12-03 博客园 CureRails所针对的是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.rbdepot>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