Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add in_realtime method #45

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/timecop/timecop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,14 @@ def return_to_baseline
def top_stack_item #:nodoc:
instance.instance_variable_get(:@_stack).last
end

# execute the block in realtime
def in_realtime(&block)
instance.send(:in_realtime, &block)
end
end


private

def baseline=(baseline)
Expand All @@ -130,6 +136,18 @@ def travel(mock_type, *args, &block) #:nodoc:
end
end

def in_realtime(&block)
current_stack = @_stack
current_baseline = @baseline
unmock!
yield
ensure
@_stack = current_stack
@baseline = current_baseline
end



def unmock! #:nodoc:
@baseline = nil
@_stack = []
Expand Down
57 changes: 57 additions & 0 deletions test/timecop_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,63 @@ def test_travel_time_returns_nil
assert_nil Timecop.travel(t_future)
end

def test_return_resets_to_current_time
t_future = Time.local(2030, 10, 10, 10, 10, 10)
t_past = Time.local(2010, 10, 10, 10, 10, 10)

Timecop.return
now = Time.now

Timecop.travel t_future
assert (Time.now - 30) > now
Timecop.in_realtime do
assert (Time.now - 30) < now
assert Time.now >= now
end

Timecop.travel t_past
assert (Time.now + 30) < now
Timecop.in_realtime do
assert (Time.now - 30) < now
assert Time.now >= now
end

assert (Time.now + 30) < now

end

class TestError < RuntimeError; end;

def test_return_resets_to_current_time_when_exceptio_occurrs
t_future = Time.local(2030, 10, 10, 10, 10, 10)
t_past = Time.local(2010, 10, 10, 10, 10, 10)

Timecop.return
now = Time.now

Timecop.travel t_future
assert (Time.now - 30) > now
assert_raises TestError do
Timecop.in_realtime do
assert (Time.now - 30) < now
assert Time.now >= now
raise TestError
end
end

Timecop.travel t_past
assert (Time.now + 30) < now
assert_raises TestError do
Timecop.in_realtime do
assert (Time.now - 30) < now
assert Time.now >= now
raise TestError
end
end

assert (Time.now + 30) < now
end

def test_travel_time_with_block_returns_the_value_of_the_block
t_future = Time.local(2030, 10, 10, 10, 10, 10)
expected = :foo
Expand Down