Some useful assertions, maybe
The first is to ensure two arrays contain the same elements not necessarily in the same order.
require 'test/unit'
require 'set'
module AssertEqualArray
def assert_equal_array(array_1, array_2)
assert_equal array_1.size, array_2.size, "Arrays must be of the same size to be equal"
assert_equal array_1.to_set, array_2.to_set
end
end
class Test::Unit::TestCase
include AssertEqualArray
end
class MyTest < Test::Unit::TestCase
def test_should_assert_equal_arrays
assert_equal_array [1, 2, 3], [2, 1, 3]
end
end
The second is to test for generated warnings. In my current project app, I use method_missing and wanted to warn the user if the unknown message looks like it’s supposed to be a payment mechanism…
day '25-oct-2006' do cash 30.29, beer end # Results in NoMethodError and, more importantly, this friendly warning.. # Maybe you expected 'cash' to be a payment mechanism? # Cool huh?
Anyway, I wanted a way to test that the warning was being generated and came up with another assertion…
require 'test/unit'
require 'stringio'
module AssertWarning
def assert_warning(expected_warning, &blk)
original_stderr = $stderr
$stderr = stderr = StringIO.new
yield
assert_equal expected_warning, stderr.string.chomp
ensure
$stderr = original_stderr
end
end
class Test::Unit::TestCase
include AssertWarning
end
class MyTest < Test::Unit::TestCase
def test_should_assert_warning
assert_warning('this is a warning') { Kernel::warn('this is a warning') }
end
end