imalik8088
imalik8088

Reputation: 1631

date based condition check in ruby

I want to check a category based on the age of a member. My test are looking like this:

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

and my method in the model is looking like this:

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

How can I implement the and freeze the time in the model in order pass the tests? Any idea

Solution

I have solved the problem in adding a parameter to my age method like this:

  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

AND MY Condition check is looking like this:

 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

Upvotes: 1

Views: 148

Answers (1)

Max
Max

Reputation: 15975

You can set up expectations on the Date class.

today = Date.parse("2012-02-02")
Date.expects(:today).returns(today)

Something like this.

Upvotes: 1

Related Questions