代码之家  ›  专栏  ›  技术社区  ›  corroded

Ruby Koan:test\nil\u是一个对象

  •  13
  • corroded  · 技术社区  · 15 年前

    我最近尝试用这个工具来提高我的rails技能:

    http://github.com/edgecase/ruby_koans

    但我在通过一些考试时遇到了困难。我也不确定我是否做了一些正确的事情,因为我的目标只是通过测试,有很多方法可以通过它,我可能做了一些不符合标准的事情。

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

    一个具体的例子:

    再过几天,

     def test_nil_is_an_object
       assert_equal __, nil.is_a?(Object), "Unlike NULL in other languages"
     end
    

    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
    

    我猜我应该在assert\u匹配中放一个“No method error”字符串,但是assert\u equal呢?

    5 回复  |  直到 7 年前
        1
  •  12
  •   Chris Heald    15 年前

    assert_equal true, nil.is_a?(Object) 确实是正确的解决办法。问题是“nils是否在Ruby对象中?”对鲁比来说,他们是。因此,为了通过断言,您应该断言该测试的真实性。

    在第二个示例中,当调用nil上的未定义方法时,会得到 NoMethodError: undefined method 'foo' for nil:NilClass NoMethodError ,消息是 undefined method 'foo' for nil:NilClass

        2
  •  5
  •   Les    14 年前

    你在跑步吗

    ruby path_to_enlightenment.rb
    

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

    另外,“记住沉默有时是最好的答案”——如果你被难倒了,不要投入任何东西,工具会帮助你。

        3
  •  2
  •   Andy_Vulhop    15 年前

    好吧,按照红-绿重构的典型TDD格言,您应该运行测试(可能在单独的控制台中使用rake)并看到失败的发生。从那里,他们向你提供了一些关于预期情况的信息。

    至于风格,koans并不是真的在教。您只需找到并阅读一些用ruby编写的代码,就可以了解ruby社区的典型惯例和习惯用法。

        4
  •  2
  •   A4J    13 年前

    简单是Ruby Koans的关键-当我开始的时候,我认为 必须

    Ruby Koans Answers

        5
  •  1
  •   traday    14 年前

    我记得当我做这件事的时候,我试着思考测试,试着投入

    <Answer> and <"Answer">
    

    要记住的是,实际的类不必是字符串或其他形式的。

    ex.class, ex.class
    

    如上所述,将代码放入irb并执行它。

    (1..5).class == Range
    

    这是一个很大的暗示

    推荐文章