Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tomstuart
Created April 30, 2014 12:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomstuart/4382332089a8402bf475 to your computer and use it in GitHub Desktop.
Save tomstuart/4382332089a8402bf475 to your computer and use it in GitHub Desktop.
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
@tomstuart
Copy link
Author

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