LoginSignup
14
11

More than 3 years have passed since last update.

RailsのSimpleCovでカバレッジレポートが出力されない場合の対処法

Last updated at Posted at 2020-03-03

環境

Ruby 2.0
Rails 4.0
simplecov 0.9.2
またテストはRSpecを使用

状況

Gemfileとspec_helper.rbは以下のように設定

Gemfile
group :test do
  # 以下追記
  gem 'simplecov', require: false
end
spec_helper.rb
# 以下追記
require 'simplecov'
SimpleCov.start 'rails'

RSpecの実行

$ bundle exec spring rspec spec

カバレッジのレポートはcoverage/index.htmlを開くと確認可能ですが、
見てみると全ての項目が100%に、つまりレポートが1つも出力されていませんでした。

対処法

最初にSimpleCov.startを実行する

SimpleCov.startの記述位置が問題となっている場合があります。
これはspec_helper.rb内の先頭に記述される必要があります。

ダメな例

spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'helpers'
# ...略
require 'simplecov'

# 適当な位置で実行
SimpleCov.start 'rails'

RSpec.configure do |config|
 # ...略
end

良い例

spec_helper.rb
# 先頭に配置
require 'simplecov'
SimpleCov.start 'rails'

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'helpers'
# ...略

RSpec.configure do |config|
 # ...略
end

より具体的には、require File.expand_path("../../config/environment", __FILE__)より先にSimleCov.startを持ってくる必要があるらしいです。

springを使用しない

rspec実行時にspringを使っていると正常に動作しません。
詳細は不明ですがspringとsimplecovは相性が良くないらしので、実行する際は

$ bundle exec rspec spec

で実行します。

まとめ

simplecovのissues見ると「レポートが出力されない」という事例がいくつかあるみたいなので、
今回紹介した方法でなおらなければissuesを漁ってみるといいかもしれません。

参考

Always 100% test coverage with Ruby 2.0p353 and Rails 4.1beta · Issue #271 · colszowka/simplecov

14
11
1

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
14
11