テストデータを大量に作ってベンチマークテストをする

テストデータでtitleカラムにindexを貼った時・貼ってない時の検索スピードを比較したいと思い、以下のようなコードを書いてみました。

 

spec/models/task_spec.rb

require 'rails_helper'
require 'benchmark'

RSpec.describe Task, type: :model do
describe '#search' do
it "benchmark of add index to title" do
99999.times{FactoryGirl.create(:task)}
task = Task.create(title: 'hellorspec', description: 'hello')
Benchmark.bm 10 do |r|
r.report "add index" do
Task.search('rspec')
end
end
end
end
end

 benchmarkライブラリをrequireし、Task.search('rspec')を実行するのにかかる時間を計測します。

以下の記事がベンチマークについて詳しく書いてくださっており、参考にさせていただきました!!

 

qiita.com

モデルファイルは以下のような実装になっております。

class Task < ApplicationRecord
validates :title, presence: true
validates :description, presence: true
enum status: [:未着手, :着手中, :完了]

def self.search(keyword = nil)
val ||= ""
where('title LIKE(?)', "%#{keyword}%")
end

end

 

コントローラーは以下のような実装です。

def index
@tasks = Task.all.order("created_at DESC").search(params[:keyword])
end

 

 

 

そして、テストを実行した結果が以下です。

上の実行結果が、indexを貼っている方、下の実行結果がindexを貼っていない方です。

indexを貼っていない方がやや早いという結果になってしまいました。。。

gyazo.com

 

 

果たしてこれが良い方法だったのかは謎ですが、テストデータを大量に作る方法や、ベンチマークテストについて学べたのでよかったです!!