Domanda

I'm doing test driven development for an assignment that's for intro to Ruby. My TestObject class is supposed to be able to be initialized with 2 parameters, a and b, but if b isn't a number then an ArgumentError should be raised. here is my initialize method, I'm not sure how to raise an exception and then handle it to prevent all of the other tests from failing as well. Any help is appreciated, my professor hasn't taught us about exceptions in Ruby yet and I haven't been able to find much help online other than trying begin, raise, rescue but that didn't work for me.

def initialize(a,b)
    @a = a
    @b = b

    raise ArgumentError unless b.is_a?
end
È stato utile?

Soluzione

As @bjhaid said. You want to

raise ArgumentError unless b.is_a?(Numeric)

Assuming you're using testunit. In your tests use:

assert_raise ArgumentError do
  WhateverYourClassIsCalled.new('something', 'something that is not a number')
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top