Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

RSpec | パラメータ化テスト

概要

パラメータ化テスト

詳細

RSpecでパラメータ化テストを行う

サンプル

仕様

漢数字の一〜十を数値として扱うようにStringクラスを拡張します。
・漢数字かどうかの検証
・漢数字から数値への変換
・漢数字同士の加算
を実装し、それをパラメータ化テストします。

実装コード
# encoding: utf-8
class String
  alias :old_plus :+
  KANSUJI = {""=>1, ""=>2, ""=>3, ""=>4, ""=>5, ""=>6, ""=>7, ""=>8, ""=>9, ""=>10}

  def kansuji_to_i
    return self unless KANSUJI.has_key? self
    KANSUJI[self]
  end

  def kansuji?
    return true if KANSUJI[self]
    false
  end

  def + (value)
    return self.kansuji_to_i + value.kansuji_to_i if self.kansuji? && value.kansuji?
    self.old_plus value
  end
end
テストコード
# encoding: utf-8
require_relative "../string"
describe "string kansuji" do 
  describe "kansuji?" do 
    cases = [
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "", expected: true},
      {value: "1", expected: false},
      {value: "", expected: false},
    ]

    cases.each do |c|
      it "#{c[:value]} is kansuji should return #{c[:expected]}" do 
        ret = c[:value].kansuji?
        expect(ret).to eq(c[:expected])
      end
    end
  end

  describe "kansuji_to_i" do 
    cases = [
      {value: "", expected: 1},
      {value: "", expected: 2},
      {value: "", expected: 3},
      {value: "", expected: 4},
      {value: "", expected: 5},
      {value: "", expected: 6},
      {value: "", expected: 7},
      {value: "", expected: 8},
      {value: "", expected: 9},
      {value: "", expected: 10},
      {value: "1", expected: "1"},
      {value: "", expected: ""},
    ]

    cases.each do |c|
      it "kansuji #{c[:value]} is number #{c[:expected]}" do 
        ret = c[:value].kansuji_to_i
        expect(ret).to eq(c[:expected])
      end
    end
  end

  describe "+" do 
    cases = [
      {value: "", addition: "", expected: 2},
      {value: "", addition: "", expected: 3},
      {value: "", addition: "", expected: 4},
      {value: "", addition: "", expected: 5},
      {value: "", addition: "", expected: 6},
      {value: "", addition: "", expected: 7},
      {value: "", addition: "", expected: 8},
      {value: "", addition: "", expected: 9},
      {value: "", addition: "", expected: 10},
      {value: "", addition: "", expected: 11},
      {value: "1", addition: "", expected: "1一"},
      {value: "", addition: "", expected: ""},
    ]

    cases.each do |c|
      it "kansuji #{c[:value]} + kansuji #{c[:addition]} is number #{c[:expected]}" do 
        ret = c[:value] + c[:addition]
        expect(ret).to eq(c[:expected])
      end
    end
  end
end
テスト結果
$ rspec
....................................

Finished in 0.006 seconds
36 examples, 0 failures