🖥

#Ruby #Rails + #rspec で rspec-benchmark gem を ”使わず" に速度検証・ベンチマークテストをする

に公開

Speed test and benchmark test "do not use" with rspec-benchmark gem with #Ruby #Rails + #rspec

ポイント

  • rspec を使うと色々とテストデータを作成/自動削除などしてくれるので、新しい仕組みを用意しなくて良い
  • rspec-benchmark gem がなぜかうまく動かなかった
  • 以下の例はデータ生成などはしていないが、 FactoryBot を組み合わせたりすると便利

速度を検証する

require 'benchmark'

describe 'sleep 5 seconds ( expect speed )' do
  subject do
    Benchmark.realtime { sleep 5 }
  end

  it { is_expected.to be < 6 }
end

# sleep 5 seconds ( expect speed )
#  should be < 6

速度は検証せず、標準出力で結果確認だけをする

require 'benchmark'

describe 'sleep 5 seconds ( not expect speed but stdout benchmark result )' do
  subject do
    Benchmark.realtime { sleep 5 }
  end

  it { puts subject }
end

# sleep 5 seconds ( not expect speed but stdout benchmark result )
# 5.003996700048447
#  example at ./spec/some_spec.rb:18

速度検証をしつつ、標準出力で結果も確認する

require 'benchmark'

describe 'sleep 5 seconds ( expect subject result and stdout benchmark result )' do
  subject do
    sleep 5
    true
  end

  it do
    subject_result = nil
    benchmark_time = Benchmark.realtime { subject_result = subject }
    puts benchmark_time

    expect(subject_result).to be true
    expect(benchmark_time).to be < 6
  end
end


# sleep 5 seconds ( expect subject result and stdout benchmark result )
# 5.005656399996951
#   should be < 6

結果の例

rspec -fd some_benchmark_spec.rb

image

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2261

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-07-11

Discussion