0

Ruby – How to Unit Test your Codes

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

Calculator Code

This file is named as SimpleCalculatorClass.rb.

Unit Test Codes

This file is named SimpleCalculatorClassTests.rb.

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 is ran once before any test method is executed.

Test::Unit.at_exit do

This is ran once after all test methods are executed.

setup method

This is ran right before each test method is executed.

teardown method

This is ran 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

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert