问题
I opened irb & entered:
require 'test/unit'
but when I used the assert_equal
method, I got following error: NoMethodError: undefined method 'assert_equal' for main:Object
. Why is this happening even after requiring 'test/unit' ?
回答1:
assert_equal
is defined on subclasses of Test::Unit::TestCase
, so are only available in that class. You may have some success with include Test::Unit::TestCase
to load those methods onto the current scope.
More likely you could be better writing your tests in a short file, and running them with ruby ./my_file.rb
回答2:
You can use in built ruby error testing
raise "Message you want to throw when error happens" if/unless "Condition when you want to throw the error "
OR
If you get error messages when trying to use assertions, like "NoMethodError: undefined method `assert' for main:Object", then add this to the top of your script:
require "test/unit/assertions"
include Test::Unit::Assertions
回答3:
This is how assertions are used:
class Gum
def crisis; -42 end
end
# and as for testing:
require 'test/unit'
class GumTest < Test::Unit::TestCase
def test_crisis
g = Gum.new
assert_equal -42, g.crisis
end
end
来源:https://stackoverflow.com/questions/12317921/why-undefined-method-assert-equal-is-thrown-even-after-requiring-test-unit