我想根据会员的年龄查看某个类别。我的测试看起来像这样:
it "should return 'CATEGORY B' if member turn 15 on the 01-11-2015" do
Timecop.freeze(Date.parse("01-11-2015"))
@member.date_of_birth = "2000-11-01"
expect(@member.category).to eq('CATEGORY B')
end
it "should return 'CATEGORY C' if member turn 15 on the 31-10-2015" do
Timecop.freeze(Date.parse("01-11-2015"))
@member.date_of_birth = "2000-10-31"
expect(@member.category).to eq('CATEGORY C')
end
我在模型中的方法看起来像这样:
def category
local_age = age
next_november = "01-11-#{Date.today.year}"
last_day_in_oktober = "31-10-#{Date.today.year}"
if local_age < 7 then
'CATEGORY A'
elsif local_age >= 7 && local_age < 15
'CATEGORY B'
elsif local_age > 15 && local_age < 40
'CATEGORY C'
elsif local_age >= 40
'CATEGORY D'
end
end
如何通过测试来实现和冻结模型中的时间?任何想法
我已经解决了向我的age方法添加参数的问题,如下所示:
def age(_date = Time.now.utc.to_date)
_date.year - date_of_birth.year - (date_of_birth.to_date.change(:year => _date.year) > _date ? 1 : 0)
end
和我的条件检查看起来像这样:
next_november = Date.parse("01-11-#{Date.today.year}")
last_day_in_oktober = Date.parse("31-10-#{Date.today.year}")
elsif age >= 7 && age(next_november) <= 15
答案 0 :(得分:1)
您可以在Date
班级设置期望值。
today = Date.parse("2012-02-02")
Date.expects(:today).returns(today)
像这样的东西。