Ruby:TDD 加编码

Ruby: TDD Plus Coding

gem 'minitest', '~> 5.2'
# TDD

require 'minitest/autorun'
require 'minitest/pride'
require_relative 'kid'

class KidTest < Minitest::Test
  def test_kid_has_not_eaten_sugar
    kid = Kid.new
    assert_equal 0, kid.grams_of_sugar_eaten
  end

  def test_kid_gets_5_grams_from_eating_candy

    kid = Kid.new
    kid.eat_candy
    assert_equal 5, kid.grams_of_sugar_eaten

    5.times { kid.eat_candy }
    assert_equal 30, kid.grams_of_sugar_eaten
  end

  def test_kid_is_not_hyperactive

    kid = Kid.new
    refute kid.hyperactive?
  end

  def test_kid_is_hyperactive_after_60_grams_of_sugar

    kid = Kid.new
    11.times { kid.eat_candy }
    refute kid.hyperactive?, "Not hyperactive yet..."
    kid.eat_candy
    assert kid.hyperactive?, "OK, now the kid is hyperactive."
  end
end

# CODE

class Kid
  attr_reader :grams_of_sugar_eaten


  def initialize
    @grams_of_sugar_eaten = 0
  end

  def eat_candy(grams = 5)
    @grams_of_sugar_eaten += grams
  end

  def hyperactive?
    false
  end
end

任何人都可以帮助指导我思考如何让第二次测试通过等等吗?

我不知道怎样才能让孩子在吃了 5 克糖后通过测试,然后 5.times 在他吃了 30 克糖后通过测试。

感谢任何帮助

您已将 eat_candy 添加为 attr_reader,而不是方法。这里的 initialize 函数将 eat_candy 设置为自身。

可能的修复:

class Kid
  attr_reader :grams_of_sugar_eaten

  def initialize
    @grams_of_sugar_eaten = 0
  end

  def eat_candy(grams = 5)
    @grams_of_sugar_eaten += grams
  end
end