Ruby - Raise exception during testing

Introduction

For example, you want to add a method to String that's designed to capitalize text into titles:

Demo

class String 
  def titleCase #  ww  w.  j  av a  2 s  .c  o m
    self.capitalize 
  end 
end 

puts "this is a test".titleCase 

raise "Fail 1" unless "this is a test".titleCase == "This Is A Test" 
raise "Fail 2" unless "another test 1234".titleCase == "Another Test 1234" 
raise "Fail 3" unless "We're testing titleCase".titleCase == "We're Testing Titleize"

Result

The last three lines of code raise exceptions unless the output of titleCase is what you expect it to be.

These tests are known as assertions, as they're asserting that a certain condition is true.

The code above fails on the first test of this test case, so let's write the code to make it work:

Demo

class String 
  def titleCase # from   w ww  .  j  a v a2  s.  c  o m
    self.gsub(/(\A|\s)\w/){ |letter| letter.upcase } 
  end 
end 
puts "this is a test".titleCase 

raise "Fail 1" unless "this is a test".titleCase == "This Is A Test" 
raise "Fail 2" unless "another test 1234".titleCase == "Another Test 1234" 
raise "Fail 3" unless "We're testing titleCase".titleCase == "We're Testing Titleize"

Result

Related Topic