Skip to content

Instantly share code, notes, and snippets.

@mixonic
Created October 26, 2011 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mixonic/1316673 to your computer and use it in GitHub Desktop.
Save mixonic/1316673 to your computer and use it in GitHub Desktop.
Stub some time for Rails, not in tests
# Lifting from http://stackoverflow.com/questions/714042/unit-testing-code-which-gets-current-time
# mostly, but adding a non-block version.
#
# Toss this into config/initializers/stub_time.rb and set a
# time at the bottom of the file.
#
# Danger Will Robinson, Danger!
#
require 'time'
class Time
def self.metaclass
class << self; self; end
end
def self.is(point_in_time)
new_time = case point_in_time
when String then Time.parse(point_in_time)
when Time then point_in_time
else raise ArgumentError.new("argument should be a string or time instance")
end
class << self
alias old_now now
end
metaclass.class_eval do
define_method :now do
new_time
end
end
if block_given?
yield
class << self
alias now old_now
undef old_now
end
end
end
end
# Time.is '2011-11-01'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment