LoginSignup
8
6

More than 3 years have passed since last update.

Ruby2.6の'oneshot coverage'を使用して本番稼働してるRailsアプリケーションのデッドコードを見つける

Last updated at Posted at 2019-09-19

Ruby2.6の'oneshot coverage'を使用して本番稼働してるRailsアプリケーションのデッドコードを見つける

この記事では、Ruby2.6から追加されたoneshot coverageを使用して、
本番稼働しているRailsアプリケーションのカバレッジを取得してデッドコードを見つける手順を説明します。

oneshot coverageとは

Ruby2.6から標準ライブラリCoveragestartメソッドに引数oneshot_lines: trueが指定する事で指定したファイルの中から行単位で実行の有無が集計できるというものです。

詳細は機能ページを確認して下さい。
https://bugs.ruby-lang.org/issues/15022
https://docs.ruby-lang.org/en/master/Coverage.html

Railsアプリケーションに適用する

1. gem 'oneshot_coverage'のインストール

gem 'oneshot_coverage'を使います。
See: https://github.com/riseshia/oneshot_coverage

railsアプリケーションの場合、リクエスト単位で実行されたファイルと行毎の実行の有無を計測してくれます。

Gemfile
gem 'rails'
# NOTE: 内部で`defined?(Rails)`を使用しているのでrailsの後に記述する
gem 'oneshot_coverage'

2. OneshotCoverage::Logger::FileLoggerをrequireする

今回は計測したカバレッジをログ出力したいので、OneshotCoverage::Logger::FileLoggerを使用します。
その為にインストールしたgemを編集する必要があります。

$ bundle open oneshot_coverageして、lib/oneshot_coverage.rbに以下の行を追加します。

require "coverage"
require "digest/md5"

require "oneshot_coverage/logger/null_logger"
+ require "oneshot_coverage/logger/file_logger"
require "oneshot_coverage/railtie" if defined?(Rails)

3. oneshot_coverageの設定ファイルを作成する

config/application.rbか、confing/initializers/oneshot_coverage.rbを作成して設定値を記述します。
See: https://github.com/riseshia/oneshot_coverage#configuration

今回はログに出力したいので、以下の様に設定します。

logfile_path = 'log/oneshot_coverage.log'
OneshotCoverage.configure(
  target_path: Rails.root,
  logger: OneshotCoverage::Logger::FileLogger.new(logfile_path),
  emit_term: nil,
)
OneshotCoverage.start

ログファイルは、rails rootのlog/oneshot_coverage.logにファイルが作成され、書き込みが行われます。

確認

rails serverでサーバーを起動してリクエストを送ると、log/oneshot_coverage.logにログが出力される事が確認できると思います。

8
6
2

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
8
6