8. Yard と SimpleCov の設定

今回は自動で Web 報告書を作成してくれるシステムを二つ紹介する。

Yard のインストール

これまで RDoc でドキュメントの記述をしていたが、今回は Yard を使ってみる。Gemfile に yard を追加する

# a documentation generation tool for the Ruby programming language
gem 'yard'

bundle install でインストールする。

$ bundle install
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Installing yard 0.8.7.6
Your bundle is complete!
It was installed into ./vendor/bundle

実際のドキュメントの書き方だが、例えば Year モデルであればこんな感じで書いてみる。

# @!attribute year
#   @return [Fixnum] 西暦
# @!attribute default_year
#   @return [Boolean] デフォルト年度であれば true
class Year < ActiveRecord::Base
  validates :year, :default_year, presence:true
  validates :year, uniqueness:true
  # @return [Year] 西暦(y)から Year オブジェクトを得る
  scope :year_value_is, -> y { where arel_table[:year].eq y }

  # @return [Year] 前年度
  def pre_year
    self.class.year_value_is(year - 1).first
  end

  # @return [Year] 次年度
  def post_year
    self.class.year_value_is(year + 1).first
  end
end

bin/rake yard もしくは binstub を作った後で、bin/yard とすると、doc の下にマニュアルセットが作成される。
先ほどの Year のページのマニュアルは以下のようになる。
規定に則ってコメントを書くだけで、綺麗なマニュアルが作成されていることがわかる。

simplecov のインストール

次に、テストのカバレッジを確認するために、Gemfile の test に simplecov を追加する

group :test do
  (中略)
  gem 'simplecov', '~> 0.9.1'
end

bundle install する。

> bundle install
Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Installing docile 1.1.5
Installing simplecov-html 0.8.0
Installing simplecov 0.9.1
Your bundle is complete!
It was installed into ./vendor/bundle

spec/spec_helper.rb に以下の文を追加する。

require 'simplecov'
SimpleCov.start do
  add_filter "/vendor/bundle/"
  add_filter “/config/“
end

これらを設定後にテストを起動するとこんな感じになる。

06:53:46 - INFO - Running: spec

Year
  should be valid
  when year is nil
    should not be valid
  when default_year is nil
    should not be valid
  when duplicate year
    should not be valid
  of 2014
    is pre year of 2015.
    is post year of 2013.

Finished in 0.37578 seconds (files took 1.71 seconds to load)
6 examples, 0 failures
Coverage report generated for RSpec to /Users/hkob/rails/webcit3/coverage. 34 / 34 LOC (100.0%) covered.

現在は、まだ 100% のカバレッジを満たしているようだ。
今後もテストの抜けがないように実装していく。
100% になっていない場合には、ブラウザで coverage/index.html を見ることでどの部分がカバーされていないかを確認することが可能である。
ただし、ハードウェア的なエラーなどどうしてもカバーできない部分もあるため、100% を保持することが目的ではなく、カバーできない理由を確認することが重要である。

今日はここまで。

written by iHatenaSync