VSCode で Ruby のカバレッジを表示する

何をしたいか

RubyKaigi 2019 に行ってカバレッジに対しての意識が高まっているので、VSCodeRubyカバレッジ(どの行が実行されて、どの行が実行されなかったか)を表示したい。

VSCode 側の設定

Coverage Gutters という拡張を入れる。 Ruby は対応していなさそうだけど大丈夫。

プロジェクト側の設定

diff --git a/Gemfile b/Gemfile
index 2139148..b02f0e1 100644
--- a/Gemfile
+++ b/Gemfile
@@ -49,6 +49,8 @@ gem 'gretel'
 gem 'chart-js-rails'

 group :development, :test do
+  gem 'simplecov'
+  gem 'simplecov-lcov'
   # Use sqlite3 as the database for Active Record
   gem 'sqlite3', '~> 1.3.6'
   # Call 'byebug' anywhere in the code to stop execution and get a debugger console

忘れずに bundle install しておく。 次に spec_helper.rbsimplecov の設定を追加する。

diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index ce33d66..6dc7db9 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -93,4 +93,13 @@ RSpec.configure do |config|
   # as the one that triggered the failure.
   Kernel.srand config.seed
 =end
+
+  require 'simplecov'
+  require 'simplecov-lcov'
+  SimpleCov::Formatter::LcovFormatter.config do |c|
+    c.single_report_path = 'coverage/lcov.info'
+    c.report_with_single_file = true
+  end
+  SimpleCov.formatter = SimpleCov::Formatter::LcovFormatter
+  SimpleCov.start 'rails'
 end

カバレッジを表示する

$ bundle exec rspec

ファイルを開いて、右クリックメニューから「Coverage Gutters: Display Coverage」をクリックする。

f:id:mallowlabs:20190512104835p:plain

どの行が実行されてどの行が実行されていないかが表示される。

f:id:mallowlabs:20190512104846p:plain

まとめ

簡単に最高の結果を手に入れた。