4

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.

B Seven
  • 44,484
  • 66
  • 240
  • 385

3 Answers3

5

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.

Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74
3

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.

Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74
1

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
Joshua Cheek
  • 30,436
  • 16
  • 74
  • 83
Bramha Ghosh
  • 6,504
  • 4
  • 30
  • 29