LoginSignup
1
0

More than 5 years have passed since last update.

Rspecでメソッドに引数として与えられたブロックをスタブに実行させる。

Posted at

概要

単体テストを記述するときは、他モジュールのメソッドをスタブとして表現し、テスト対象メソッドのロジックのみをテストできるようにしなくてはいけない。
テスト対象のメソッドが、他モジュールのメソッドに渡されたブロックの中で実行されている時、
他モジュールのメソッドをスタブにしつつ、そのスタブに渡されたブロックの中でテスト対象のメソッドを実行する方法について記す。


解決策

スタブを宣言する際に、その末尾にブロックを付与し、その呼び出しを付与してやれば良い。


例えば下記のようなメソッドにおいて、test_targetをテストしたいとする。

test_target
def example_method(argument)
  other_module_object.stubed_method do
    test_target_method(argument)
  end
end

この時、other_module_objectstubed_methodはブロックを引数に取るメソッドである。
テスト対象のメソッドはtest_target_methodなので、stubed_methodに渡されたブロックが実行されなければテスト対象のコードを実行できない。

この時、stubed_methodに対する記述を下記のようにしてやることで、stubed_methodに渡されたブロックを実行させることができる。

test_code
allow(other_module_object).to receive(:stubed_method) { |&dummy_block| dummy_block.call }

参考
http://rspec.info/documentation/3.5/rspec-mocks/#Arbitrary_Handling

1
0
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
1
0