Assertions in Ruby

Assertions in Ruby

This article will introduce the assertions in Ruby and the types of assertions with examples.

Assertions in Ruby

Ruby allows us to do things that any other compiled languages don’t allow us. The best thing that Ruby provides is assertions.

Ruby provides an assert() method for testing modules and can generate results whether a module is passed. Testing is one of the main parts of software development.

Software that has not been tested can cause huge problems if launched. Before launching any module or a complete software, we need to test all the software modules.

In this tutorial, we will go through many types of assertions in Ruby. There are different types of assertions that can be used for different types of testing.

the assert() Method in Ruby

If we want to test the function or a test, we can use the simple assert() method and pass the function or a test that needs to be tested. We also need to pass the error message displayed if the test fails.

# ruby
assert(isString(12), "This is a number")

the assert_equal() Method in Ruby

If we want to test if the expected result is the same as the actual result, we can use another method, assert_equal(), that takes in the expected result, actual result, and the failure message.

The syntax of this method is shown below.

# ruby
assert_equal(true, isString(12), "This is a number")

If we want to use the method in reverse, Ruby provides another method, assert_not_equal(), that takes in the same parameters as the assert_equal() method.

the assert_not_nil() Method in Ruby

There is another mainly used method, assert_not_nil(), that is used to check if the function has returned anything or not. If the function has not returned anything, it will output a failure message.

The syntax of this function is shown below.

# ruby
assert_not_nil(getJson(), "No response from Server!")

Some other methods can be used in Ruby assertions, but those methods are not used more often.