Ruby Koan:test_nil_is_an_object

cor*_*ded 13 ruby

我最近尝试用这个工具磨练我的rails技能:

http://github.com/edgecase/ruby_koans

但我在通过一些测试时遇到了麻烦.此外,我不确定我是否正确地做了一些事情,因为目标只是通过测试,有很多方法可以通过它,我可能正在做一些不符合标准的事情.

有没有办法确认我做得对吗?

一个具体的例子:

在about_nil,

 def test_nil_is_an_object
   assert_equal __, nil.is_a?(Object), "Unlike NULL in other languages"
 end
Run Code Online (Sandbox Code Playgroud)

所以它告诉我检查第二个子句是否等于一个对象(所以我可以说nil是一个对象)或者只是assert_equal true, nil.is_a?(Object)因为该语句是真的而放?

和下一个测试:

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
  # What happens when you call a method that doesn't exist.  The
  # following begin/rescue/end code block captures the exception and
  # make some assertions about it.
  begin
    nil.some_method_nil_doesnt_know_about
  rescue Exception => ex
    # What exception has been caught?
    assert_equal __, ex.class

    # What message was attached to the exception?
    # (HINT: replace __ with part of the error message.)
    assert_match(/__/, ex.message)
  end
end
Run Code Online (Sandbox Code Playgroud)

我猜我应该在assert_match中放一个"No method error"字符串,但是assert_equal呢?

Chr*_*ald 10

assert_equal true, nil.is_a?(Object)确实是正确的解决方案.问题是"在Ruby对象中是否存在nils?",而在Ruby的情况下,它们是.因此,为了传递断言,你应该断言该测试的真实性.

在第二个例子中,当你在nil上调用一个未定义的方法时,你会得到NoMethodError: undefined method 'foo' for nil:NilClass.因此,异常类是NoMethodError,而消息是undefined method 'foo' for nil:NilClass.在控制台中测试失败的行为,并查看从中获得的内容,然后将该知识应用于测试.


Les*_*Les 5

你在跑步吗?

ruby path_to_enlightenment.rb
Run Code Online (Sandbox Code Playgroud)

在更正每个测试后的命令提示符下?它会给你很多帮助.

另外"记住沉默有时候是最好的答案" - 如果你难过,不要放任何东西,工具会帮助你.