Skip to content

Instantly share code, notes, and snippets.

@ParthBarot-BoTreeConsulting
Last active October 13, 2015 18:17
Show Gist options
  • Save ParthBarot-BoTreeConsulting/42441543dcb8592f409c to your computer and use it in GitHub Desktop.
Save ParthBarot-BoTreeConsulting/42441543dcb8592f409c to your computer and use it in GitHub Desktop.
How to write tests?
  1. Identify what are diff. use cases we need to test, and define 'test' method for each. For the above example, we need,
  • breaking_fact
    • test for 0
    • test for 1
    • test for any other number (say 3)
    • test for big number, which should break and throw exception.
  • fact
    • test for 0
    • test for 1
    • test for any other number
    • test for big number.
  1. Use assertions to test the outcome, with appropriate message. All cases should cover all possible cases by which we can call the method, i.e all positive/negative cases.
  2. Test it using command 'ruby factorial_test.rb'
class Factorial
#
# This method calculates factorial using recursion, it breaks after \
# some limit (say for number more than 8000) So we can not use it for \
# calculating factorial for big numbers.
#
def self.breaking_fact(n=1)
return 1 if n == 0
n * breaking_fact(n-1)
end
#
# Calculates factorial without looping, and using simple while loop.
# This works like a charm.
#
def self.fact(n=1)
return 1 if n == 0
count = n
total = 1
while count > 1 do
total *= count
count -= 1
end
total
end
end
require 'minitest/autorun'
require_relative 'factorial'
class FactorialTest < Minitest::Test
def test_breaking_fact_factorial_of_3
assert_equal Factorial.breaking_fact(3), (3 * 2 * 1), "breaking_fact(3) should be 6"
end
def test_breaking_fact_factorial_of_1
refute_equal Factorial.breaking_fact(1), (1 * 0), "breaking_fact(1) should not be 0"
end
def test_breaking_fact_factorial_of_0
refute_equal Factorial.breaking_fact(0), (0 * -1), "breaking_fact(0) should not be 0"
end
def test_breaking_fact_factorial_of_8999
err = assert_raises SystemStackError do
Factorial.breaking_fact(8999)
end
assert_match /stack level too deep/, err.message
end
def test_fact_factorial_of_3
assert_equal Factorial.fact(3), (3 * 2 * 1), "fact(3) should be 6"
end
def test_fact_factorial_of_1
refute_equal Factorial.fact(1), (1 * 0), "fact(1) should not be 0"
end
def test_fact_factorial_of_0
refute_equal Factorial.fact(0), (0 * -1), "fact(0) should not be 0"
end
def test_fact_factorial_of_8999
assert Factorial.fact(8999).is_a?(Numeric), "should be a number"
end
end
@ParthBarot-BoTreeConsulting
Copy link
Author

Thanks @zenspider for suggesting the improvements.

  1. assert !Factorial.fact(8999).nil?, "should be a number” doesn’t test that it is a number. Just not nil.
  2. no no no. Use assert_equal and refute_equal to get good error messages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment