Take the 2-minute tour ×

I want to use an assert to raise an error within a rake task.

the_index = items.index(some_item)
assert_not_nil the_index, "Lookup failed for the following item: " + some_item

I get undefined method assert_not_nil. Can I include the assertions file in my rake task? How?

Is this a best practice, or is there a better way to do it?

Working in Ruby 1.9.2.

share|improve this question
Unit testing and exception handling are two very different things. –  Mark Thomas Dec 15 '11 at 3:15
add comment

3 Answers

up vote 3 down vote accepted

There is a built-in Array#fetch method that acts like #[] but raises an IndexError instead of returning nil when the element is not found. (The same applies for Hash.) I always use the first one if I don't expect the collection to exclude an element.

a = [:foo, :bar]
a.fetch(0)   #=> :foo
a[4]         #=> nil
a.fetch(4)   #=> IndexError: index 4 outside of array bounds: -2...2

And for the other cases raise exceptions yourself like Bramha Ghosh suggests:

raise "I don't expect this to be nil!" if element.nil?

However, you shouldn't be doing this often, only if you know that your code will fail far away making debugging painful.

share|improve this answer
add comment

You can actually use assertions wherever you want.

require "minitest/unit"
include MiniTest::Assertions # all assertions are in this module
refute_nil @ivar, "An instance variable should not be nil here!"

But why would you do that? Raise meaningful exceptions yourself instead.

share|improve this answer
add comment

is there a special reason you want to use an assert?

Why not

raise IndexError, "Lookup failed for the following item: #{some_item}" unless items.include? some_item
share|improve this answer
To make it look like unit tests. It makes it more readable. –  B Seven Dec 26 '11 at 19:00
add comment

Your Answer


