This post demonstrates how to unit test your Ruby codes. Note that Ruby-on-Rails (RoR) is not used here.
Installation Details
- Windows 10
- Ruby 2.3.1
- ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
The Ruby Application
The ruby application is a simple Calculator program that can add, subtract, multiple, and divide integral numbers.
Directory Structure
We have a simple directory structure for our application. Under the src folder, we have rb and tests folders.
- rb – contains our Calculator codes
- tests – contains our unit tests
[wp_ad_camp_2]
Calculator Code
This file is named as SimpleCalculatorClass.rb.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class SimpleCalculatorClass def add(a, b) return a + b end def sub(a, b) return a - b end def mul(a, b) return a * b end def div(a, b) return a / b end end |
Unit Test Codes
This file is named SimpleCalculatorClassTests.rb.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | require 'test/unit' require_relative '../rb/SimpleCalculatorClass' class SimpleCalculatorClassTests < Test::Unit::TestCase Test::Unit.at_start do puts 'START: runs only once at start' end Test::Unit.at_exit do puts 'END: runs only once at end' end def setup puts "Runs before each test method" @cal = SimpleCalculatorClass.new() end def teardown puts "Runs after each test method" end def test_add() assert_equal(2, @cal.add(1,1)) end def test_sub() assert_equal(0, @cal.sub(1,1)) end def test_mul() assert_equal(12, @cal.mul(4,3)) end def test_div() assert_equal(1, @cal.div(4,3)) end end |
There are several things to take notice of.
require ‘test/unit’
We import the test/unit module. This is something similar to importing Junit in Java.
require_relative ‘../rb/SimpleCalculatorClass’
We include our SimpleCalculator.rb script into this unit test so that we can use the SimpleCalculatorClass class.
Test::Unit::TestCase
Unit test classes extend from Test::Unit::TestCase
Test::Unit.at_start
This runs once before any test method is executed.
Test::Unit.at_exit do
This runs once after all test methods are executed.
setup method
This runs right before each test method is executed.
teardown method
This runs right after each test method is executed.
test_* methods
These are your test methods
Sample Test Output
Download the codes
https://github.com/Turreta/Ruby-How-to-Unit-Test-your-Codes