3
1

More than 5 years have passed since last update.

Rspec3 カスタムフォーマットの例(CSV出力)

Last updated at Posted at 2016-03-07

Rspec3のカスタムフォーマットについて

さるやんごとない理由により、Selenium Webdriverのテスト結果をCSVファイルに残す必要が出てきた。
色々調べたけれど、「フォーマットを書く人はソースコード読むだろうから後はKIAIとKONJOでがんば」みたいに書かれており、
MAJIかよハードルたけえな、と思ったので、備忘録。
Rspec3+Selenium Webdriverで、結果としてCSVファイルを吐き出させる。

環境
* Ruby 2.2.4
* Rspec 3.4.3
* Selenium-webdriver

カスタムフォーマッタ

以下のように記載。registerで書いてあげないといけない、と。

# -*- coding: utf-8 -*-
require 'pp'
require 'csv'
require 'rspec'
RSpec::Support.require_rspec_core "formatters/base_formatter"

class CsvFormatter < RSpec::Core::Formatters::BaseFormatter
   RSpec::Core::Formatters.register self,  :example_passed, :example_failed, :createResult, :output_csv

  def initialize(output)
    super(output)
    @results = Array.new
  end

  def example_passed(notification)
    result = createResult_ok(notification)
    result[:result] = "Pass"
    @results << result
  end

  def example_failed(notification)
    result = createResult_ng(notification)
    result[:result] = "Fail"
    @results << result  
  end

  def close(notification)
    output_csv()
  end

  def createResult(notification)
      {
      #Run Date
      :run_date => notification.example.metadata[:run_date],
      #Test Name
      :test_name => notification.example.metadata[:test_name],
      # テスト番号
      :number => notification.example.metadata[:number],
    }
  end

  def output_csv
    CSV.open("result.csv","w") do |csv|
      @results.each do |result|
        csv << result.values
      end
    end
  end
end

Seleniumでの記載方法

itブロックで、Metadataを指定してあげる。

it "テストほげほげ" , :run_date => "2014/03/22", :test_name => "ほげらー", :number =>"1"  do
   ・・・・・
end

スクリプトの実行方法

フォーマッタファイルを-rで指定し、使うクラスをformatで指定。

rspec -r ./csv_formatter.rb it_ruby.rb --format CsvFormatter

結果として、CSVで吐き出される。

3
1
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
3
1