Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

RSpec | スタブ

概要

スタブ

詳細

スタブはメソッド呼び出し時に特定の値を戻します。

サンプル

引数で指定されたオブジェクトから生成された乱数と
内部で生成された乱数を元にしたテキストを返却するクラスのテストを行うとします。

テスト対象

# encoding: utf-8
class Hoge
  def hoge(hage)
    "hoge#{hage.random1}-#{random2}"
  end

  def random2
    rand 100
  end
end

class Hage
  def random1
    rand 100
  end
end

Spec

# encoding: utf-8
require_relative "../hoge"
describe "hoge" do 
  it "hoge returns hoge" do 
    hoge = Hoge.new

    # 引数やフィールドから設定出来る要素の場合
    hage = double('hage')
    # hage = double('hage', random: 50) =>メソッドのスタブとまとめてこのような書き方も可能
    hage.stub(:random1).and_return('50')

    # 引数やフィールドから設定出来ない、内部利用のみの処理をスタブ化する場合
    Hoge.any_instance.stub(random2: "25")

    ret = hoge.hoge hage

    expect(ret).to eq("hoge50-25")
  end
end

テスト結果

hoge hoge returns hoge
$rspec
.

Finished in 0.003 seconds
1 example, 0 failures