Ruby, Ruby Tutorial

Ruby – How to Unit Test your Codes

ruby block port create Class Object

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.

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 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

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like