rspecのテストでカバレッジが計測できるgem、SimpleCovを導入する

テストを書くならカバレッジ計測と行単位で通った・通ってないの確認ができたらいいな、と思っていたら
@tmtms さんより「SimpleCov」を教えていただきました。

GitHub - colszowka/simplecov: Code coverage for Ruby 1.9+ with a powerful configuration library and automatic merging of coverage across test suites

導入手順

Gemfileに「simplecov」を追加

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
  gem 'rspec-rails'
  # Test format nyan cat
  gem 'nyan-cat-formatter'
  # テストを自動実行
  gem 'spring-commands-rspec'
  gem 'guard-rspec', require: false
  # カバレッジ取得
  gem "simplecov"
  # モデルにテーブルのカラムをコメントで出力
  gem 'annotate'
end

gemをインストール

$ bundle install --path vendor/bundle --jobs=4
$ # .bundle/configに設定されている場合はbundleでOK

spec/spec_helper.rbにsimplecovのstartを記述

require 'simplecov'

SimpleCov.start 'rails'

RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
#・・・略・・・

これで準備は完了

使い方

rspecでテストを実行する。

$ bundle exec rspec spec/

するとプロジェクトフォルダ直下に「coverage」というフォルダが作成される。

f:id:maetoo11:20160411194209p:plain

coverageフォルダ配下の「index.html」をブラウザで開く。

f:id:maetoo11:20160411194648p:plain

するとファイルごとのカバレッジ一覧が表示される。

f:id:maetoo11:20160411195350p:plain

ファイル名をクリックすれば、行単位で通った・通っていないが確認できる。

f:id:maetoo11:20160411195827p:plain


導入にあたり参考にしたサイト