要从DOB计算生日bday = Date.strptime("1980,6,10","%Y,%m,%d")
,您必须执行此类操作以考虑闰年。
def age(dob)
now = Time.now.utc.to_date
now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end
# age(bday) => 34
我的问题是上面的代码是怎样的,与此不同:
def age2(dob)
((Date.today - dob)/365).to_f.floor
end
# age2(bday) => 34
作为开发人员,这种示例只是可怕,因为如果不小心,它会在代码中引入一个脏bug。
那么你将如何为此编写一个合适的测试?
答案 0 :(得分:0)
每年实际上超过365天0.242199天。因此,要使此错误显着,您可以将其构建长达一年,或者测试年度过早计算的阈值情况。
此脚本演示了两者。它使用您发布的三个版本的年龄。
require 'date'
def age1(dob)
now = Time.now.utc.to_date
now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end
def age2(dob)
((Date.today - dob)/(1.0/365.0)/365/365).floor
end
def age3(dob)
((Date.today - dob)/365.0).to_f.floor
end
year = Time.now.year - (1 / 0.242199)
now = Time.now.utc.to_date
bd = Date.new(year,now.month,now.day + 1);
puts "Testing Date: #{bd}"
puts "using age1 - #{age1(bd)}"
puts "using age2 - #{age2(bd)}"
puts "using age3 - #{age3(bd)}"
year = Time.now.year - (365 / 0.242199)
bd = Date.new(year,1,1)
puts "Testing Date: #{bd}"
puts "using age1 - #{age1(bd)}"
puts "using age2 - #{age2(bd)}"
puts "using age3 - #{age3(bd)}"
输出:
Testing Date: 2009-06-13
using age1 - 4
using age2 - 5
using age3 - 5
Testing Date: 0506-01-01
using age1 - 1508
using age2 - 1509
using age3 - 1509