Ruby 用RSpec进行性能测试

Ruby 用RSpec进行性能测试,ruby,unit-testing,rspec,Ruby,Unit Testing,Rspec,我试图将性能测试合并到非Rails应用程序的测试套件中,但遇到了一些问题 我不需要每次都运行性能测试,如何排除它们?注释和取消注释config.filter\u run\u排除:perf=>true似乎是个坏主意 如何报告基准测试结果?我认为RSpec对此有某种机制 在spec/spec\u helper.rb class MessageHelper class << self def messages @messages ||= [] end

我试图将性能测试合并到非Rails应用程序的测试套件中,但遇到了一些问题

  • 我不需要每次都运行性能测试,如何排除它们?注释和取消注释
    config.filter\u run\u排除:perf=>true
    似乎是个坏主意
  • 如何报告基准测试结果?我认为RSpec对此有某种机制

  • spec/spec\u helper.rb

    class MessageHelper
      class << self
        def messages
          @messages ||= []
        end
    
        def add(msg)
          messages << msg
        end
      end
    end
    
    def message(msg)
      MessageHelper.add msg
    end
    
    RSpec.configure do |c|
      c.filter_run_excluding :perf => !ENV["PERF"]
    
      c.after(:suite) do
        puts "\nMessages:"
        MessageHelper.messages.each {|m| puts m}
      end
    end
    
    class-MessageHelper
    类我创建了rubygem,用于在RSpec中编写性能测试。它对测试速度、资源使用和可伸缩性有很多期望

    例如,要测试代码的速度,请执行以下操作:

    expect { ... }.to perform_under(60).ms
    
    或者与其他实现进行比较:

    expect { ... }.to perform_faster_than { ... }.at_least(5).times
    
    或测试计算复杂性:

    expect { ... }.to perform_logarithmic.in_range(8, 100_000)
    
    或查看分配了多少对象:

    expect {
      _a = [Object.new]
      _b = {Object.new => 'foo'}
    }.to perform_allocation({Array => 1, Object => 2}).objects
    
    要过滤测试,您可以将规范分离到
    性能
    目录中,并添加一个rake任务

    require 'rspec/core/rake_task'
    
    desc 'Run performance specs'
    RSpec::Core::RakeTask.new(:perf) do |task|
      task.pattern = 'spec/performance{,/*/**}/*_spec.rb'
    end
    
    然后在需要时运行它们:

    rake perf