Skip to content

Commit

Permalink
Allow time to be frozen
Browse files Browse the repository at this point in the history
  • Loading branch information
sos4nt committed May 26, 2020
1 parent 34a1ec9 commit 95fe7a2
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 42 deletions.
8 changes: 0 additions & 8 deletions lib/site_prism/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,6 @@ class InvalidUrlMatcherError < PageLoadError; end
# Formerly known as `NoSelectorForElement`
class InvalidElementError < SitePrismError; end

# A tool like Timecop is being used to "freeze time" by overriding Time.now
# and similar methods. In this case, our waiter functions won't work, because
# Time.now does not change.
# If you encounter this issue, check that you are not doing Timecop.freeze without
# an accompanying Timecop.return.
# Also check out Timecop.safe_mode https://github.com/travisjeffery/timecop#timecopsafe_mode
class FrozenInTimeError < SitePrismError; end

# The condition that was being evaluated inside the block did not evaluate
# to true within the time limit
# Formerly known as `TimeoutException`
Expand Down
35 changes: 12 additions & 23 deletions lib/site_prism/waiter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,22 @@

module SitePrism
class Waiter
class << self
def wait_until_true(wait_time = Capybara.default_max_wait_time)
start_time = Time.now

loop do
return true if yield
break if Time.now - start_time > wait_time

sleep(0.05)

check_for_time_stopped!(start_time)
end

raise SitePrism::TimeoutError, "Timed out after #{wait_time}s."
def self.wait_until_true(wait_time = Capybara.default_max_wait_time)
done = wait_time.zero?
thread = Thread.start do
sleep wait_time
done = true
end

private

def check_for_time_stopped!(start_time)
return unless start_time == Time.now
loop do
return true if yield
break if done

raise(
SitePrism::FrozenInTimeError,
'Time appears to be frozen. For more info, see ' \
'https://github.com/site-prism/site_prism/blob/master/lib/site_prism/error.rb'
)
sleep(0.05)
end
raise SitePrism::TimeoutError, "Timed out after #{wait_time}s."
ensure
thread.kill
end
end
end
11 changes: 0 additions & 11 deletions spec/site_prism/waiter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,5 @@
expect(duration).to be_within(0.1).of(timeout)
end
end

context 'when time is frozen' do
before do
allow(Time).to receive(:now).and_return(Time.new(2019, 4, 25))
end

it 'throws a FrozenInTimeError exception' do
expect { described_class.wait_until_true { false } }
.to raise_error(SitePrism::FrozenInTimeError)
end
end
end
end

0 comments on commit 95fe7a2

Please sign in to comment.