• Stars
    star
    3,333
  • Rank 12,874 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 15 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A gem providing "time travel", "time freezing", and "time acceleration" capabilities, making it simple to test time-dependent code. It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call.

timecop

Gem Version Build Status

DESCRIPTION

A gem providing "time travel" and "time freezing" capabilities, making it dead simple to test time-dependent code. It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call.

INSTALL

bundle add timecop

FEATURES

  • Freeze time to a specific point.
  • Travel back to a specific point in time, but allow time to continue moving forward from there.
  • Scale time by a given scaling factor that will cause time to move at an accelerated pace.
  • No dependencies, can be used with any ruby project
  • Timecop api allows arguments to be passed into #freeze and #travel as one of the following:
    • Time instance
    • DateTime instance
    • Date instance
    • individual arguments (year, month, day, hour, minute, second)
    • a single integer argument that is interpreted as an offset in seconds from Time.now
  • Nested calls to Timecop#travel and Timecop#freeze are supported -- each block will maintain its interpretation of now.
  • Works with regular Ruby projects, and Ruby on Rails projects

USAGE

Run a time-sensitive test

joe = User.find(1)
joe.purchase_home()
assert !joe.mortgage_due?
# move ahead a month and assert that the mortgage is due
Timecop.freeze(Date.today + 30) do
  assert joe.mortgage_due?
end

You can mock the time for a set of tests easily via setup/teardown methods

describe "some set of tests to mock" do
  before do
    Timecop.freeze(Time.local(1990))
  end

  after do
    Timecop.return
  end

  it "should do blah blah blah" do
  end
end

Set the time for the test environment of a rails app -- this is particularly helpful if your whole application is time-sensitive. It allows you to build your test data at a single point in time, and to move in/out of that time as appropriate (within your tests)

in config/environments/test.rb

config.after_initialize do
  # Set Time.now to September 1, 2008 10:05:00 AM (at this instant), but allow it to move forward
  t = Time.local(2008, 9, 1, 10, 5, 0)
  Timecop.travel(t)
end

The difference between Timecop.freeze and Timecop.travel

freeze is used to statically mock the concept of now. As your program executes, Time.now will not change unless you make subsequent calls into the Timecop API. travel, on the other hand, computes an offset between what we currently think Time.now is (recall that we support nested traveling) and the time passed in. It uses this offset to simulate the passage of time. To demonstrate, consider the following code snippets:

new_time = Time.local(2008, 9, 1, 12, 0, 0)
Timecop.freeze(new_time)
sleep(10)
new_time == Time.now # ==> true

Timecop.return # "turn off" Timecop
Timecop.travel(new_time)
sleep(10)
new_time == Time.now # ==> false

Timecop.scale

Let's say you want to test a "live" integration wherein entire days could pass by in minutes while you're able to simulate "real" activity. For example, one such use case is being able to test reports and invoices that run in 30 day cycles in very little time, while also being able to simulate activity via subsequent calls to your application.

# seconds will now seem like hours
Timecop.scale(3600)
Time.now
# => 2012-09-20 21:23:25 -0500
# seconds later, hours have passed and it's gone from 9pm at night to 6am in the morning
Time.now
# => 2012-09-21 06:22:59 -0500

See #42 for more information, thanks to Ken Mayer, David Holcomb, and Pivotal Labs.

Timecop.safe_mode

Safe mode forces you to use Timecop with the block syntax since it always puts time back the way it was. If you are running in safe mode and use Timecop without the block syntax Timecop::SafeModeException will be raised to tell the user they are not being safe.

# turn on safe mode
Timecop.safe_mode = true

# check if you are in safe mode
Timecop.safe_mode?
# => true

# using method without block
Timecop.freeze
# => Timecop::SafeModeException: Safe mode is enabled, only calls passing a block are allowed.

Rails v Ruby Date/Time libraries

Sometimes Rails Date/Time methods don't play nicely with Ruby Date/Time methods.

Be careful mixing Ruby Date.today with Rails Date.tomorrow / Date.yesterday as things might break.

Contribute

timecop is maintained by travisjeffery, and was created by jtrupiano.

Here's the most direct way to get your work merged into the project.

  • Fork the project
  • Clone down your fork
  • Create a feature branch
  • Hack away and add tests, not necessarily in that order
  • Make sure everything still passes by running tests
  • If necessary, rebase your commits into logical chunks without errors
  • Push the branch up to your fork
  • Send a pull request for your branch

More Repositories

1

jocko

Kafka implemented in Golang with built-in coordination (No ZK dep, single binary install, Cloud Native)
Go
4,850
star
2

ClangFormat-Xcode

Xcode plug-in to to use clang-format from in Xcode and consistently format your code with Clang
Objective-C
2,885
star
3

proglog

grpc log service example project
Go
168
star
4

TRVSNavigationControllerTransition

Push/pop transition entire UINavigationController views.
Objective-C
151
star
5

LingusticTaggerDemo

< 80 LOC Implementing Writer Pro's syntax control (with NSLinguisticTagger) that iA tried to patent
Objective-C
107
star
6

TRVSURLSessionOperation

NSURLSession and NSOperationQueue working together
Objective-C
103
star
7

TRVSMonitor

ObjC synchronization construct with the ability to wait until signalled that a condition was met.
Objective-C
79
star
8

TRVSEventSource

Server-sent events EventSource client using NSURLSession
Objective-C
78
star
9

proto-go-sql

Generate SQL Scanner and Valuer implementations for your Protobufs.
Go
76
star
10

ecs-deploy

CLI tool to easily update your ECS services.
Go
64
star
11

mocha-teamcity-reporter

JavaScript
41
star
12

kube-leaderelection

Leader election for your own services, building on Kubernetes' APIs/etcd.
Go
31
star
13

terraform-provider-kafka

Terraform provider for managing Kafka topics.
Go
27
star
14

kafka-proxy

Proxy requests to Kafka with middleware.
Go
27
star
15

go-dynaport

A Go library for getting free ports, dynamically.
Go
24
star
16

validates_phone_number

Adds validation methods to ActiveModel for validating phone numbers.
Ruby
23
star
17

dotfiles

@travisjeffery's dotfiles. emacs, zsh
Shell
21
star
18

kafka-statsd

Send your Kafka offset lags to StatsD.
Go
20
star
19

sinon-rails

Sinon.js for Rails
Ruby
20
star
20

certmagic-sqlstorage

SQL storage for CertMagic/Caddy TLS data.
Go
20
star
21

go-fastbqstreamer

A fast BigQuery streaming client for Go (Golang).
Go
18
star
22

go-bqloadbatcher

A BigQuery client to batch and load data with Go (Golang).
Go
17
star
23

mocker

Mock pkg/generating tool for Go.
Go
17
star
24

deets

Library to get browser details. Name, version, size, etc.
JavaScript
15
star
25

grpc-go-kit-error-example

Go
14
star
26

TRVSRainbowRoad

iOS lib to animate your labels like Mario Kart's Rainbow Road
Objective-C
14
star
27

awesome-wm

My configuration of the awesome window manager.
Lua
14
star
28

ios-how-to-mask-and-shadow

iOS-How-to-MaskAndShadow
Objective-C
14
star
29

jasmine-jquery-rails

Jasmine-jQuery for Rails
Ruby
12
star
30

snipmate-snippets

my snippets that I use with snipmate
Vim Script
12
star
31

proced-narrow

Live-narrowing of search results for proced in Emacs.
Emacs Lisp
12
star
32

datadog-terraform-example

Managing Datadog with Terraform example
HCL
11
star
33

ecs-exec

Run commands on your ECS container instances.
Go
10
star
34

vimperator-scripts

vimperator plug-ins, color schemes and etc I've written
JavaScript
8
star
35

go-batcher

Simple batch library for Golang.
Go
8
star
36

TRVSKit

a collection of useful apis for objc, ios, mac hacking
Objective-C
8
star
37

tumblr.tmbundle

TextMate bundle for interfacing with Tumblr.
7
star
38

ec2-tag-spots

Create tags for AWC EC2 spot fleets.
Go
7
star
39

NSDictionary-TRVSUnderscoreCamelCaseAdditions

Convert NSDictionary keys to/from under_score/camelCase. Useful when working with JSON APIs, etc.
Objective-C
7
star
40

hubot-socket.io

Socket IO adapter for Hubot.
CoffeeScript
7
star
41

emacs-tumblr

Post to Tumblr using Emacs.
Emacs Lisp
6
star
42

computer-science

Data structures, algorithms, and other good stuff.
Objective-C
6
star
43

eshell-z.el

quickly jump to directories in emacs's eshell
Emacs Lisp
6
star
44

vim-auto-mkdir

vim: automatically mkdir when writing file in nonexistent directory
Vim Script
6
star
45

fang

Remove boilerplate using spf13/cobra with spf13/viper.
Go
6
star
46

vim-script-installer

rakefile to install vim scripts downloaded from github and other git repos
5
star
47

nyancat

Animated nyan cat in the terminal written in Go
Go
5
star
48

vim-colors

good vim color themes i've hacked together
Vim Script
5
star
49

vim-gotosymbol

Go to Symbol for Vim with Tagslist.
Vim Script
4
star
50

vimperator-config

see name
JavaScript
4
star
51

will_paginate_twitter_bootstrap

Make will_paginate and Bootstrap, from Twitter work together.
Ruby
4
star
52

hal

Campfire bot.
CoffeeScript
4
star
53

emacs-nav

Nav is a lightweight solution for Emacs users who want something like TextMate's file browser, or the Eclipse project view. Unlike these two, Nav only shows the contents of a single directory at a time, but it allows recursive searching for filenames using the 'f' key-binding, and recursive grepping of file contents with the 'g' key-binding. Nav can be run painlessly in terminals, where Speedbar either fails on its attempt to make a new frame or is hidden. Nav's terminal-friendliness comes from running in the frame where it was started, keeping window management simple. The Nav key bindings are simple, as well -- each key command is a single keystroke long.
Emacs Lisp
4
star
54

retry

Go
3
star
55

go-book

Go
3
star
56

iwantmyname-ddns

Shell
3
star
57

how-to-functional-options

Go
3
star
58

vim-testee

super duper testing plugin/extension for Vim
Vim Script
3
star
59

iterm-open.app

Utility for opening iTerm, the best terminal for the Mac, from the Finder.
3
star
60

clojure-fractal

makin' fractals with clojure
Clojure
3
star
61

go-ec2-metadata

Go pkg to get metadata about running ec2 instances.
Go
3
star
62

PackBot

NodeJS/Faye chatbot with ICanHaz/Moustache Templating, etc.
JavaScript
3
star
63

OpenInMacVim.app

Ported OpenInTextMate over for MacVim users, thus OpenInMacVim.
2
star
64

edi-generator

Ruby
2
star
65

mongo-to-elasticsearch

Load Mongo collections into Elasticsearch.
Go
2
star
66

testerical

Efficiently run tests for Ruby, including Ruby on Rails projects within Vim.
Vim Script
2
star
67

project-euler

Project Euler Solutions
Python
2
star
68

hub.el

hub.el helps you win at git with emacs
Emacs Lisp
2
star
69

om-nom-moize

tasty memoization
Ruby
2
star
70

haskell-repl

simple repl made in/for haskell
Haskell
2
star
71

grpcerr-metadata

Go
2
star
72

errors.js

JavaScript
2
star
73

Reddit

a reddit iOS app without using any 3rd party libs such as afnetworking or mantle
Objective-C
2
star
74

TRVSKeyboardState

Objective-C
2
star
75

judy

rainbow animate your links
JavaScript
2
star
76

twitter_bootstrap

Gem for using Bootstrap, from Twitter on Rails.
Ruby
2
star
77

skydome

Chrome extension to replace 'Rogers Centre' with the true name SkyDome.
JavaScript
2
star
78

urbandict.me

Unofficial API for Urban Dictionary
JavaScript
2
star
79

thr-client

The Heavy Rotation - show your Rdio heavy rotation on your site
JavaScript
2
star
80

burrow-stats

Go
1
star
81

gomodlib

Go
1
star
82

vim-rails-find-partial

Vim Script
1
star
83

pdf_renderer

Ruby
1
star
84

go-tron

Go
1
star
85

ooc-lang.tmbundle

textmate bundle for ooc-lang
1
star
86

terraform-provider-semaphoreci

Shell
1
star
87

go-simplelog

Go pkg that makes logging simple.
Go
1
star
88

homebrew.app

homebrew with a graphical user interface
C
1
star
89

benchmarks

Ruby
1
star
90

travisjeffery.github.com

personal website and blog
HTML
1
star
91

robot-wars

good thing noone will have to clean up the pieces
Clojure
1
star
92

UITableView-TRVSEmptyView

Easiest way to show an empty/placeholder view for UITableViews.
Objective-C
1
star
93

notebox

Note keeping sidekick.
Ruby
1
star
94

thr-lambda

The Heavy Rotation - show your Rdio heavy rotation on your site
JavaScript
1
star
95

yodlee-client

Yodlee client for Go.
Go
1
star
96

stash.cool

http://stash.cool
CSS
1
star
97

vim-help

Mappings for navigating vim help docs.
Vim Script
1
star
98

vim-jump-x2

Navigate jumps motions by buffers.
Vim Script
1
star
99

ChromeGitHubSwitcher

GitHub Header/Implementation File Switcher Extension for Chrome
JavaScript
1
star
100

jays

Web app that scrapes the web for Toronto Blue Jays streams
JavaScript
1
star