test/spy/test_subroutine.rb in spy-1.0.1 vs test/spy/test_subroutine.rb in spy-1.0.2

- old
+ new

@@ -4,10 +4,14 @@ class TestSubroutine < Minitest::Test def spy_on(base_object, method_name) Subroutine.new(base_object, method_name).hook end + def spy_on_instance_method(base_object, method_name) + Subroutine.new(base_object, method_name, false).hook + end + def setup @pen = Pen.new end def teardown @@ -107,10 +111,19 @@ assert_equal result.reverse, @pen.write(result) assert_empty @pen.written end + def test_spy_and_return_can_call_a_block_with_hash + result = "hello world" + + spy_on(@pen, :write_hash).and_return { |**opts| opts[:test] } + + assert_equal result, @pen.write_hash(test: result) + assert_empty @pen.written + end + def test_spy_and_return_can_call_a_block_raises_when_there_is_an_arity_mismatch write_spy = spy_on(@pen, :write) write_spy.and_return do |*args| end write_spy.and_return do |string, *args| @@ -133,9 +146,76 @@ result = @pen.write_block do string end assert_equal string, result + end + + def test_spy_and_call_through_returns_original_method_result + string = "hello world" + + write_spy = spy_on(@pen, :write).and_call_through + another_spy = spy_on(@pen, :another).and_call_through + + result = @pen.write(string) + + assert_equal string, result + assert write_spy.has_been_called? + assert_equal 'another', @pen.another + assert another_spy.has_been_called? + end + + def test_spy_and_call_through_with_hash_original_method + string = 'test:hello world' + + write_spy = spy_on(@pen, :write_hash).and_call_through + + @pen.write_hash(test: 'hello world') + assert_equal string, @pen.written.last + assert write_spy.has_been_called? + end + + def test_spy_on_instance_and_call_through_returns_original_method_result + string = "hello world" + + inst_write_spy = spy_on_instance_method(Pen, :write).and_call_through + inst_another_spy = spy_on_instance_method(Pen, :another).and_call_through + + result = @pen.write(string) + + assert_equal string, result + assert inst_write_spy.has_been_called? + assert_equal 'another', @pen.another + assert inst_another_spy.has_been_called? + end + + def test_spy_on_instance_and_call_through_with_hash + string = 'test:hello world' + + inst_write_spy = spy_on_instance_method(Pen, :write_hash).and_call_through + + @pen.write_hash(test: 'hello world') + + assert_equal string, @pen.written.last + assert inst_write_spy.has_been_called? + end + + def test_spy_on_instance_and_call_through_to_aryable + to_aryable = Class.new do + def hello + 'hello' + end + + def to_ary + [1] + end + end + + inst_hello_spy = spy_on_instance_method(to_aryable, :hello).and_call_through + inst = to_aryable.new + + assert_equal 'hello', inst.hello + assert inst_hello_spy.has_been_called? end def test_spy_hook_records_number_of_calls pen_write_spy = spy_on(@pen, :write) assert_equal 0, pen_write_spy.calls.size