Created
February 18, 2016 09:03
-
-
Save pirj/d4e2e069a482e89348c7 to your computer and use it in GitHub Desktop.
Allow Capybara to walk hand in hand with freezed time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Due to Capybara's intolerance to tools that freeze time | |
# (specifically Time.now), we only freeze Time.current here | |
# @param time [Time] Time. But may be anything else if you like | |
# @example | |
# TimeFreezer.freeze_current_time('lol') do | |
# Time.current #=> lol | |
# Time.now #=> Your system time | |
# end | |
# Time.current #=> Your time with respect to Time.zone | |
# | |
# spec/rails_helper.rb | |
# RSpec.configure do |config| | |
# config.include TimeFreezer | |
# end | |
# | |
module TimeFreezer | |
extend ActiveSupport::Concern | |
def freeze_current_time time | |
freeze time | |
yield | |
ensure | |
unfreeze | |
end | |
private | |
def freeze time | |
ActiveSupport::TimeZone.class_eval do | |
alias_method :old_now, :now | |
end | |
ActiveSupport::TimeZone.send(:define_method, :now) { time } | |
end | |
def unfreeze | |
ActiveSupport::TimeZone.class_eval do | |
remove_method :now | |
alias_method :now, :old_now | |
remove_method :old_now | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment