Skip to content

Instantly share code, notes, and snippets.

@carols10cents
Created April 18, 2016 21:46
Show Gist options
  • Select an option

  • Save carols10cents/8117b24375de4b3cf7414209619c4b8a to your computer and use it in GitHub Desktop.

Select an option

Save carols10cents/8117b24375de4b3cf7414209619c4b8a to your computer and use it in GitHub Desktop.
Test Recursion, grossly
# code under test, you'll need to know their method name.
# I've made two here to show the tests passing and failing
class Heart
def self.some_recursive_method(num)
if num > 0
Heart.some_recursive_method(num - 1)
end
end
def self.some_non_recursive_method(num)
3 + 4 # whatevs
end
end
require 'minitest/autorun'
require_relative './heart'
class RecursionTest < Minitest::Test
@@recursive_calls = 0
class << Heart
alias :old_some_recursive_method :some_recursive_method
def some_recursive_method(num)
# Check out cool other info in `caller`
if !caller.first.match(/^#{__FILE__}/)
@@recursive_calls += 1
end
old_some_recursive_method(num)
end
alias :old_some_non_recursive_method :some_non_recursive_method
def some_non_recursive_method(num)
if !caller.first.match(/^#{__FILE__}/)
@@recursive_calls += 1
end
old_some_non_recursive_method(num)
end
end
def test_recursion_happened
@@recursive_calls = 0
Heart.some_recursive_method(3)
assert @@recursive_calls > 0
end
def test_that_should_fail_since_recursion_doesnt_happen
@@recursive_calls = 0
Heart.some_non_recursive_method(3)
assert @@recursive_calls > 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment