LoginSignup
1
0

More than 3 years have passed since last update.

RSpecデータリクエストを削減してテスト実行時間を削減した話

Posted at

はじめに

私はエンジニアインターンで主にサーバーサイドの開発を担当させていただいています。

機能実装の際はRSpecでテストケースを書いてから実装していて、コミットする前に全体のテストを通してバグを見つけているのですが

実行時間が長い!

ということで、RSpecのリファクタリングを行いテストの実行時間を削減して見ましたので、一部紹介したいと思います。

1. 従来のRSpecでのデータリクエスト状況

現状、RSpecでは以下のように、letを使用してデータの作成を行っています。

require 'spec_helper'

describe User do
  let!(:user) { FactoryBot.create(:user) }

  it 'anything' do
    # userのテスト
  end

  it 'anything' do
    # userのテスト
  end

  it 'anything' do
    # userのテスト
  end
end

これではexampleが3回行われる度にUserモデルが作成されてしまう。
これをどうにか1回のレコード作成に留められないか...

2. gem "test-prof"の導入

そこでtest-profを導入します。

Gemfile
gem "test-prof"
bundle install

変更後テストケース

require 'spec_helper'

describe User do
  let_it_be(:user) { FactoryBot.create(:user) }

  it 'anything' do
    # userのテスト
  end

  it 'anything' do
    # userのテスト
  end

  it 'anything' do
    # userのテスト
  end
end

このようにtest-profはlet_it_beというヘルパーメソッドを提供してくれるgemになります。

そうするとRailsのトランザクションテスト機能を利用してレコードを最初に1回だけ作成して、テストが終了したら該当データを削除してくれるようになります。

3. ベンチマーク

変更したテストファイル数は全体の3割ほどですが、約1分のテスト実行時間の削減に繋がりました。

let_it_be使用前

スクリーンショット 2021-03-12 18.12.38.png

let_it_be使用後

スクリーンショット 2021-03-12 18.46.49.png

おわりに

画期的にテストの実行時間を削減できた訳ではありませんが、長期的に見て効果のある対処法なのではないかと思います。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0