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 # from  ww  w.ja  v a2  s .  c om
    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 #   w w w.  j  a va  2  s.com
    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