LoginSignup
6
4

More than 5 years have passed since last update.

ブロックの中身をテストするときのRSpecの書き方

Posted at
block_spec.rb
class Sample
  def foo(x)
    ho = hoge(x) do |y|
      piyo(y)
    end
    ho + 'foo'
  end

  def hoge(x)
    yield x + 'hoge'
  end

  def piyo(y)
    y + 'piyo'
  end
end


describe Sample do
  it 'yields block of hoge method by passing block to stub' do
    allow(subject).to receive(:hoge).with('start') do |x, &block|
      expect(block.call(x)).to eq('startpiyo')
      'startpiyo'
    end
    subject.foo('start')
  end

  it 'yields block of hoge method by using `and_yield`' do
    allow(subject).to receive(:hoge).with('start').and_yield('yielded_arg')
    expect(subject.foo('start')).to eq('yielded_argpiyofoo')
  end
end

上記2つのどちらかの方法でテストする。

参考

6
4
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
6
4