LoginSignup
13
13

More than 5 years have passed since last update.

RSpecの出力をカスタマイズする方法

Last updated at Posted at 2013-09-22

RSpecの出力をカスタマイズする方法。
例えばテスト中に計測した統計情報とか、そういうものを出力内容に含めたい時に便利。

結論から言うと、自分でFormatterやPrinterを作って、RSpecにこれを使え、って指定すれば良い。

# コマンド例
rspec -r my_html_formatter.rb -r my_html_printer.rb --format MyHtmlFormatter myapp_spec.rb

「-r」は外部のソースファイルを読み込ませるオプション。
そのファイルに書かれてるクラスや関数などが、specファイルの中で使用可能になる。

「--format」はFormatterの指定 (クラス名を書く、ファイル名じゃないよ!)。
Formatterは当然別ファイルに書かなきゃいけないので、別途「-r」で読み込んでおく。

Printerは実際に出力するHtmlソースなどを記述する。


オレオレFormatterの書き方だけど、RSpec内のデフォルトのFormatterクラスを継承して、
好きなように書き換えれば良い。こんな感じ。

require 'rspec/core/formatters/html_formatter'
require 'my_printer'

class MyHtmlFormatter < RSpec::Core::Formatters::HtmlFormatter

  # 例えばテスト成功時、通常出力の後に、オレオレ出力を出したいとする
  def example_passed(example)
      super
      @printer.print_my_result
  end
end

詳しくはRSpecのソースコードを参照


RSpecではFormatterは「あれを出力して、次にこれを、最後にそれを出力」みたいな
ことを書いてるに過ぎなくて、実際のHTMLソースはPrinterが持っている。

これもコードを見てみよう

これも継承して、オレオレ出力用のメソッドを追加しておこう。

require 'rspec/core/formatters/html_printer'

class MyHtmlPrinter < RSpec::Core::Formatters::HtmlPrinter

  def print_my_result
    @output.puts "<div>"
    @output.puts "なんか役に立つ結果!"
    @output.puts "</div>"
  end

end

既存の表記やデザインが気に食わないなら、
print_example_passed とか print_example_failed などをいじってみよう。

実際には、あれもこれもとカジュアルに追加できるようなHtml構造にはなっていなくて、
適当にブロックを追加してみたらデザインが崩れた…、なんてこともあるので、
割と細かい調整が必要になってしまうかもしれない。


なお、テスト中に色々なデータを集めたりするには、
before, after, each を上手に活用してみよう。

13
13
0

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
13
13