Categories
Beginners code ruby ruby on rails rubygem unit tests

Read Minitest To Learn Ruby

I continue my quest to master Ruby. Lately I’ve been reading the source code for Minitest. Minitest is a Ruby gem to help developers write unit tests. In addition, you can also use Minitest to write specs and do your development BDD style. The gem also has support for mocking and benchmarking.

Let’s concentrate our attention on the assertions.rb file located at https://github.com/seattlerb/minitest/blob/master/lib/minitest/assertions.rb. Inside that file, we can see that the assert method takes 2 parameters: test and msg. Below is the actual Ruby code.

##
#  Fails unless +test+ is truthy

def assert test, msg = nil
  self.assertions += 1
  unless test then
    msg ||= "Failed assertion, no message given."
    msg = msg.call if Proc === msg
    raise Minitest::Assertion, msg
  end
  true
end

The first line inside the assert method, self.assertions += 1, is increasing the assertions variable by 1. This value is display after your unit tests are run. Something like 10 assertions, 5 pass, 5 failed. Next we see the unless keyword followed by test and a block. Having the comment above this method, really helps us understand what unless is. The unless block will be executed if test is false. Inside that block, we set a default message to msg if msg is nil or false. The next line checks if the msg passed to our method is a Proc object. If msg is a Proc object, msg will be assigned the value returned from invoking the block. To learn more about the Proc class, go to the official Ruby docs. Then we raise an exception by calling Minitest::Assertion and passing the msg variable.

After executing the unless block, we return true.

I believe Minitest is an excellent resource to learn Ruby. It’s a small code base compared to other projects.