rubyonrails:Ruby on rails开发从头来(windows)( 2十 9)- 性能测试

  Rails所针对是Web项目必须要考虑大访问量情况所以我们来看看在Rails怎样进行性能测试

  1.    要进行性能测试我们首先要模仿大量数据我们现在知道在test/fixtures/目录下yml文件里添加我们测试数据在运行测试时这些数据会被加载到数据库但是条两条数据还可以数据多情况下条在yml文件里写可不行所以我们先看看怎样在yml文件里造大量数据在fixtrue目录下创建个子目录performance在里面新建order.yml文件把内容改成下面样子:

# Read about fixtures at http://ar.rubyonrails.org/es/Fixtures.html
<% for i in 1..100 %>
order_<%= i %>:
  id: <%= i %>
  name: Fred
  email: fred@flstones.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'
OrderTest < Test::Unit::TestCase
 fixtures :products
 HOW_MANY = 100
 def up
  @controller = StoreController.
  @request = ActionController::TestRequest.
  @response = ActionController::TestResponse.
  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"
 end
end


  在这里我们没有直接加载100个order而是在test_save_bulk_orders思路方法中先使用elapsedSeconds = Benchmark::realtime来计算测试花费时间再通过create_fixtures思路方法指定我们要加载orderyml文件然后对每条加载order进行保存在通过断言判断是否了indexAction和Flash中内容最后再判断elapsedSeconds是否小于3秒

  还有点要注意这里实际上对每个order进行了两次Save操作次是在加载yml文件时候次是我们save_order时候

  3.    如果我们不想在每个测试运行时候都从yml文件里加载数据那么我们可以通过self.use_transactional_fixtures来控制例如:

OrderTest < Test::Unit::TestCase
 fixtures :products
 self.use_transactional_fixtures = true
 HOW_MANY = 100
 ……
end


  4.    如果我们想知道某个思路方法或某句代码所花费时间可以通过rails脚本script/profiler and script/benchmarker来查看例如我们注意到Product这个Modelsearch思路方法比较慢为了避免盲目地进行优化我们使用Profiler来告诉我们每句代码使用了多少时间例如:

depot>ruby script/performance/profiler "Product.salable_items"

  注意这里script路径我在instantrails里和书上如果提示脚本找不到那就在自己本地目录找找看profiler文件放在什么地方

  5.    我们还可以使用benchmarker来比较两个思路方法所消耗时间例如:

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

  输出结果是:

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


  在这里书上写是两个思路方法的间用“”来分割在我机器上是使用个空格来分割

Tags:  rubyonrails安装 rubyrails rubyonrails教程 rubyonrails

延伸阅读

最新评论

发表评论