Ron Lockwood-Childs Unit testing in Ruby What is unit testing? * test code while writing it, as opposed to waiting until external code can exercise it for its intended purpose * fine-grained testing that tests down to individual methods within an object * validation code that accompanies application code What good is unit testing? Multiple benefits: * cheaper to catch bugs early in the implementation phase * built-in regression testing for existing code * simple way to exercise edge cases and boundary conditions * a good accompaniment to well-commented code and design documentation that gives clear examples of the expected inputs and outputs * suits the test-driven programming style. In this paradigm, the expected results from the code are written first, as a sort of low-level design doc * a good investment that can prevent the evolution of a large, brittle code base maintainers are afraid to touch - needs to be kept up with the code, can require substantial changes along with refactoring (e.g. merged objects) - will only catch the bugs the designer thinks of or are found in the field and added to unit test suite, not a reason for overconfidence How does Ruby handle unit testing? * start with shape example module RegularPolygons class InvalidNumberSides < Exception end class InvalidSideLength < Exception end class RegularPolygon attr_reader :n_sides, :side_length def initialize( n_sides, side_length ) # check parameters end def perimeter # n_sides * side_length, code incorrectly at first end def interior_angles # 360 / n_sides end def containing_circle_radius # ?? end end end # a 2-d shape must have > 2 sides # a 2-d shape must have side_lengths > 0 require 'regular_shapes' require 'test/unit' class RegularShapeValidation < Test::Unit::TestCase include RegularPolygons def test_regular_polygon_creation # create valid regular polygons and make sure they won't fail # create broken regular polygons and make sure they fail end def test_regular_polygon_perimeter # create regular polygons and make sure their perimeters come out right end # same for interior angle calc end ------- Next demo the parameter validation code & unit tests ------- Questions