1

嗨,我参加了 Lase 练习 os Learn 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("death", "You dead.")" 并且它有效,但问题是下一个对象的描述非常长,所以我的问题是:

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

1 回答 1

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
    
于 2014-05-11T10:28:32.257 回答