我正在使用exercism.io完成Ruby练习。我目前正在研究闰年问题。
这是我的代码:
class Year
DIVISORS = [4, 100, 400]
def self.leap?(year)
if is_year_leap?(year)
"Yes, #{year} is a leap year"
else
"No, #{year} is not a leap year"
end
end
def self.is_year_leap?(year)
divisible_by = multiple_of(year)
if !divisible_by[4]
false
elsif divisible_by[400]
true
end
end
def self.multiple_of(year)
DIVISORS.each_with_object({}) do |divisor, multiple|
multiple[divisor] = year % divisor == 0
end
end
end
(请注意,代码尚未完成,但在我测试1997年时,它给了我正确的答案)。
测试套件如下:
require 'date'
require 'minitest/autorun'
require_relative 'leap'
class Date
def leap?
throw "Implement this yourself instead of using Ruby's implementation."
end
alias_method :gregorian_leap?, :leap?
alias_method :julian_leap?, :leap?
end
class YearTest < Minitest::Test
def test_leap_year
assert Year.leap?(1996), 'Yes, 1996 is a leap year'
end
def test_non_leap_year
refute Year.leap?(1997), 'No, 1997 is not a leap year'
end
def test_non_leap_even_year
skip
refute Year.leap?(1998), 'No, 1998 is not a leap year'
end
def test_century
skip
refute Year.leap?(1900), 'No, 1900 is not a leap year'
end
def test_fourth_century
skip
assert Year.leap?(2400), 'Yes, 2400 is a leap year'
end
end
运行我的代码时遇到的失败是:
1) Failure:
YearTest#test_non_leap_year [leap_test.rb:20]:
No, 1997 is not a leap year
5 runs, 2 assertions, 1 failures, 0 errors, 3 skips
You have skipped tests. Run with --verbose for details.
为什么我的测试失败了?我认为它得到了正确答案,因为1997年不是闰年,但这不符合考验。
答案 0 :(得分:1)
您的leap?
方法应该只返回true
或false
,而不是您要返回的字符串。
消息(&#39;是,1996年是闰年&#39;等)附加到测试并在测试失败时显示。测试并不是要求您实际返回这些消息。
答案 1 :(得分:0)
leap?
方法返回一个字符串,而不是布尔值,因此您应该使用assert_equal
测试其输出:
assert_equal 'No, 1997 is not a leap year', Year.leap?(1997)