Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

RSpec | matcherの戻り値に応じて後処理を行う

概要

matcherの戻り値に応じて後処理を行う

詳細

matcherの戻り値に応じて後処理を行います。

RSpecのmatcherは成功時にtrue、失敗時にnilを返すので
それを判断基準に処理を分岐して、Procを実行させてみます。

前提

rspec_piccoloを利用します

構成

$ tree
Gemfile
lib
┣ hoge.rb
┗ spec
    | hoge_spec.rb
    ┗ spec_helper.rb

実装

# encoding: utf-8

module Hoge
  class Core
    def hoge(message)
      message
    end
  end
end

テスト

# encoding: utf-8
require "spec_helper"
require "hoge"

describe Hoge::Core do
  context :hoge do
    success = Proc.new do
      puts "success!!!!!!!!!!!!"
    end

    failure = Proc.new do
      puts "failure!!!!!!!!!!!!"
    end

    cases = [
      {
        case_no: 1,
        case_title: "valid case",
        input: "hoge",
        expected: "hoge",
        success_hook: success,
        failure_hook: failure
      },
      {
        case_no: 2,
        case_title: "invalid case",
        input: "invalid",
        expected: "hoge",
        success_hook: success,
        failure_hook: failure
      },
    ]

    cases.each do |c|
      it "|case_no=#{c[:case_no]}|case_title=#{c[:case_title]}" do
        begin
          case_before c

          # -- given --
          hoge_core = Hoge::Core.new

          # -- when --
          actual = hoge_core.hoge c[:input]

          # -- then --
          ret = expect(actual).to eq(c[:expected])
        ensure
          case_after c
          later = ret ? c[:success_hook] : c[:failure_hook]
          later.call
        end
      end

      def case_before(c)
        # implement each case before
      end

      def case_after(c)
        # implement each case after
      end
    end
  end
end

実行結果

無事結果に応じてProcを呼び出し出来ました

$ rspec
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}
failure!!!!!!!!!!!!
Fsuccess!!!!!!!!!!!!
.

Failures:

  1) Hoge::Core hoge |case_no=2|case_title=invalid case
     Failure/Error: ret = expect(actual).to eq(c[:expected])

       expected: "hoge"
            got: "invalid"

       (compared using ==)
     # ./spec/hoge_spec.rb:46:in `block (4 levels) in <top (required)>'

Finished in 0.002 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/hoge_spec.rb:35 # Hoge::Core hoge |case_no=2|case_title=invalid case

Randomized with seed 32099