Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Person#age gives the wrong answer for a person who hasn’t had their birthday yet this year
require 'active_support/time'
require 'active_support/testing/time_helpers'
require 'rspec/expectations'
include ActiveSupport::Testing::TimeHelpers
include RSpec::Matchers
class Person < Struct.new(:birthday)
def age
Date.today.year - birthday.year
end
end
today = Date.new(2014, 4, 30) # => Wed, 30 Apr 2014
travel_to today
my_fiftieth_birthday = 1.week.from_now.to_date # => Wed, 07 May 2014
the_day_i_was_born = my_fiftieth_birthday - 50.years # => Thu, 07 May 1964
me = Person.new(the_day_i_was_born) # => #<struct Person birthday=Thu, 07 May 1964>
expect(me.age).to eq 49
# RSpec::Expectations::ExpectationNotMetError:
# expected: 49
# got: 50
Owner

tomstuart commented Apr 30, 2014

This code is part of How testability can help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment