how do you assert an exception from another ruby module is thrown? (using assert_throws)
Asked Answered
J

1

6

I'm trying to write code like this:

assert_throws(:ExtractionFailed) { unit.extract_from('5 x 2005')}

ExtractionFailed is a trivial subclass of Exception, and under test/unit, I'm trying to assert that it is thrown when I call unit.extract_from(... bad data...)

I've moved ExtractionFailed into the SemanticText module, so now test/unit says:

<:ExtractionFailed> expected to be thrown but
<:"SemanticText::ExtractionFailed"> was thrown.

I tried writing assert_throws(:SemanticText::ExtractionFailed) {...} but I got the rather confusing message: TypeError: SemanticText is not a class/module

I can make it work by doing the following (although it seems like a hack):

  assert_throws(SemanticText::ExtractionFailed.to_s.to_sym) { unit.extract_from('5 x 2005')}

So what's the right way to say this assertion in ruby?

Jeffereyjefferies answered 24/11, 2009 at 16:47 Comment(0)
B
7

Put quotes around the symbol name after the colon e.g.

assert_throws(:"SemanticText::ExtractionFailed") { unit.extract_from('5 x 2005')}

The quotes are necessary for a symbol that contains colons or other special characters.

If you try :"SemanticText::ExtractionFailed".class in irb you will see that it is a Symbol, removing the need to use to_s and/or to_sym.

Boilermaker answered 24/11, 2009 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.