I am trying to get used to testing my code with simple driver snippets and want to test whether an Argument Error is thrown without escaping out of the program. Here is the code I am using
class Die
def initialize(sides)
@sides=sides
unless @sides>0
raise ArgumentError.new("Your number sucks, yo")
end
end
#returns the number of sides of a die
def sides
@sides
end
#generates a random die roll based on the number of sides
def roll
rand(@sides)+1
end
end
And here is what I am attempting to call to get a test.
p bad=Die.new(0)=="Your number sucks, yo"
What I want it to return is "true". What it does return in the terminal is :
w3p1_refact.rb:33:in `initialize': Your number sucks, yo (ArgumentError)
from w3p1_refact.rb:69:in `new'
from w3p1_refact.rb:69:in `<main>'
Can I rewrite this to return what I am looking for?
From the documentation of Exception
So once I have just raised exception in the
$!
global variable, I can useException#message
method, which returns the exception’s message or name.You use
Kernel#raise
I would do as below :
The above inline rescue code can be written as also :