ビットの海

ゆるふわソフトウェアエンジニアしゃぜのブログ

serverspecの結果を雑にslack通知させる為のrspecカスタムフォーマッタ書いた

Jenkinsとかから実行してる時は、そっちでやればいいんだけど、単体でcronとか実行してるときに通知させたいなーと思って。

前提

  • rspec3系
  • serverspecとしてふつーに動く状態
  • slack incoming webhookのurlをとっておく

Gemfileにslack-notifierたす

source 'https://rubygems.org'

gem 'serverspec'
gem 'rake'
gem 'slack-notifier'

lib/slack_formatter.rbを書く

require 'rspec'
require 'slack-notifier'

RSpec::Support.require_rspec_core "formatters/base_formatter"

class SlackFormatter < RSpec::Core::Formatters::BaseFormatter
  RSpec::Core::Formatters.register self, :example_passed, :example_failed

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

  def example_passed(notification)
    @results << "OK"
  end

  def example_failed(notification)
    @results << "NG"
  end

  def close(notification)
    post_slack()
  end

  def post_slack
    notifier = Slack::Notifier.new('webhook-url')

    if @results.include?("NG") then
      note = {
        text: "ダメー",
        color: "warning"
      }
    else
      note = {
        text: "おっけー",
        color: "good"
      }
    end

    notifier.post text: "", attachments: [note]
  end

end

.rspecにSlackFormatterの記述をたす

--color
--format d
--format SlackFormatter

実行するときはこんなかんじ

bundle exec rake spec:all -t -r ./lib/slack_formatter.rb

通知の内容を細かくアレコレしたいときは、slack_formatter.rbの中身をちゃんと書こう。

おしまい。