Skip to content

Instantly share code, notes, and snippets.

@dv
Created October 20, 2018 15:02
Show Gist options
  • Save dv/ef939400e3bbd589d20bc03fd1f80bfc to your computer and use it in GitHub Desktop.
Save dv/ef939400e3bbd589d20bc03fd1f80bfc to your computer and use it in GitHub Desktop.
This circumvents the no-nesting rule of the new `travel_to` in Rails TimeHelpers
# The new `travel_to` does not allow nested calls, and instead throws the following error
# in your face whenever you try to use it:
#
# Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing.
#
# Using this module to override `travel_to` will solve that issue.
#
# Note: not guaranteed to work perfectly
#
module BetterTravelTo
# The original `travel_to` does not allow nesting
def travel_to(*args, &block)
already_travelling = simple_stubs.stubbing(Time, :now)
right_now = Time.now
super(args.first, &nil)
if block
result = block.call
if already_travelling
super(right_now, &nil)
else
travel_back
end
result
end
end
end
RSpec.configure do |config|
config.include ActiveSupport::Testing::TimeHelpers
config.include BetterTravelTo
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment