由于引发了LocalJumpError异常而导致测试失败(Ruby)

时间:2011-08-07 12:32:01

标签: ruby unit-testing exception testunit

我想我搜索了一个关于我的问题的答案,但我没有看到任何回应它的帖子。所以这是关于LocalJumpError的另一个问题......

我是Ruby中的一个相对新手,我刚刚决定在我编写的所有Ruby内容之前遵循良好的实践并编写测试。

但是我在这里遇到了一些我不明白的问题。这是我的测试:

class TestFilesInfoLoggerHashCreation < Test::Unit::TestCase
   def setup
      @logger = FilesInfoLogger
   end
   # some other tests
   def test_shall_not_raise_an_exception_if_argument_is_a_string
     assert_nothing_raise @logger.get_log('foo')
   end
end

以下是应该验证上述特定测试的代码:

module FilesInfoLogger
  extend self
  def get_log(list)
     hash = Hash.new {||h,k| h[k] = (block_given?)? yield(k):''}
     if list.respond_to? :each 
       list.each {|file| hash[file]}
     else
       ([]<< list).each {|file| hash[file]}
     end
  end
end

所以当我用irb运行FilesInfoLogger.get_log('foo')时,一切似乎都运行正常,我的意思是什么都没有提出来。但是当我运行测试时,它无法返回:

test_shall_not_raise_an_exception_if_argument_is_a_string(TestFilesInfoLoggerHashCreation) [test/files_info_logger_test.rb:43]:
{"foo"=>""}.
 Exception raised:
 <#<LocalJumpError: no block given (yield)>>.

我不明白为什么根据测试单元提出一个关于没有给出块的异常,特别是因为我用block_given?测试了这个条件。我错过了什么?

感谢您的回答。

1 个答案:

答案 0 :(得分:0)

看起来assert_nothing_raised期望一个块作为参数。相反,您传递的是调用@logger.get_log('foo')的结果。试试这个:

assert_nothing_raised do
  @logger.get_log('foo')
end