Ruby:TDD编码实践——如何让Minitest测试用例通过?
Let's walk through how to get your test cases passing, step by step. First, let's recap your current code and the issues you're facing:
Your Test Code
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
Current Kid Implementation
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
Step 1: Troubleshoot the Second Test Case
First, let's look at the test for sugar accumulation. Your eat_candy method actually looks correct—it adds 5 grams each time (with a default parameter) and updates the instance variable properly.
If this test is failing, double-check:
- Did you accidentally use
=instead of+=ineat_candy? (Your current code uses+=, which is right.) - Is the
attr_reader :grams_of_sugar_eatencorrectly exposing the instance variable? (Yes, that's set up properly.) - Try adding a debug
puts kid.grams_of_sugar_eatenin the test to see what the actual value is at each step—this can help catch unexpected behavior.
Assuming your code is exactly as you posted, this test should pass! If it's not, a simple typo is the most likely culprit.
Step 2: Fix the Hyperactivity Test
The big issue is the hyperactive? method—it currently always returns false, which fails the final test. Let's align it with the test requirements:
- The test expects the kid to not be hyperactive at 55 grams (11 * 5)
- The kid should become hyperactive once they hit 60 grams (12 * 5)
Update the hyperactive? method to check the accumulated sugar:
def hyperactive? @grams_of_sugar_eaten >= 60 end
This will return true only when the kid has eaten 60 or more grams of sugar, which matches exactly what your test expects.
Step 3: Final Working Kid Class
Here's the revised implementation that will pass all tests:
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? @grams_of_sugar_eaten >= 60 end end
Run your tests again, and all cases should now pass!
内容的提问来源于stack exchange,提问作者cjl85

