Assert_equal未定义的局部变量LRTHW ex52

时间:2014-05-11 09:49:40

标签: ruby assert learn-ruby-the-hard-way

嗨,我参加了激烈的练习,学习Ruby The Hard Way,我来到了墙上......

这是测试代码:

def test_gothon_map()
    assert_equal(START.go('shoot!'), generic_death)
    assert_equal(START.go('dodge!'), generic_death)

    room = START.go("tell a joke")

    assert_equal(room, laser_weapon_armory)
end

这是它应该测试的文件的代码:

class Room

  attr_accessor :name, :description, :paths

  def initialize(name, description)
    @name = name
    @description = description
    @paths = {}
  end

  def ==(other)
    self.name==other.name&&self.description==other.description&&self.paths==other.paths
  end

  def go(direction)
    @paths[direction]
  end

  def add_paths(paths)
    @paths.update(paths)
    end

end

generic_death = Room.new("death", "You died.")

当我尝试启动测试文件时,出现错误:

generic_death = Room.new("death", "You died.")

我试着在test_gothon_map方法中设置“generic_death = Room.new(”死亡“,”你死了。“)”但它有效,但问题是对下一个对象的描述非常长,所以我的问题是:

  • 为什么断言不响应已定义的对象?
  • 可以通过将整个对象放到测试方法中来做不同的方式,因为下一个对象的描述非常长......

1 个答案:

答案 0 :(得分:0)

本地变量的本质是,它们是本地。这意味着它们在定义的范围之外不可用。

这就是为什么ruby不知道你的测试中generic_death的含义。

您可以通过以下几种方式解决此问题:

  • 在Room类中将房间定义为常量:

    class Room
      # ...
    
      GENERIC_DEATH = Room.new("death", "You died.")
      LASER_WEAPON_ARMORY = Room.new(...)
    end
    
    def test_gothon_map()
      assert_equal(Room::START.go('shoot!'), Room::GENERIC_DEATH)
      assert_equal(Room::START.go('dodge!'), Room::GENERIC_DEATH)
    
      room = Room::START.go("tell a joke")
    
      assert_equal(room, Room::LASER_WEAPON_ARMORY)
    end
    
  • 通过名称或其他标识符声明房间:

    def test_gothon_map()
      assert_equal(START.go('shoot!').name, "death")
      assert_equal(START.go('dodge!').name, "death")
    
      room = START.go("tell a joke")
    
      assert_equal(room.name, "laser weapon armory")
    end