1

こんにちは、Lase エクササイズ os に到達しました。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 die.")" を設定しようとしましたが、うまくいきましたが、次のオブジェクトの説明が非常に長いことが問題なので、私の質問は次のとおりです。

  • 定義されたオブジェクトにアサーションが応答しないのはなぜですか?
  • 次のオブジェクトの説明が非常に長いため、オブジェクト全体をテストメソッドに入れることによって、別の方法で実行できますか...
4

1 に答える 1

0

ローカル変数の性質は、それらが local であるということです。これは、定義された範囲外では使用できないことを意味します。

そのため、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 に答える