aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorGaurish Sharma <contact@gaurishsharma.com>2015-11-09 18:57:11 +0530
committerGaurish Sharma <contact@gaurishsharma.com>2015-11-09 18:57:11 +0530
commit06adda5f3b7e622d08c1d87ec326d59df55e122f (patch)
tree5239f57da1f3657bb1272949aafca4ecfcf4effd /guides
parent41b469d0995dd482f3fd4dfbae80770df0479883 (diff)
downloadrails-06adda5f3b7e622d08c1d87ec326d59df55e122f.tar.gz
rails-06adda5f3b7e622d08c1d87ec326d59df55e122f.tar.bz2
rails-06adda5f3b7e622d08c1d87ec326d59df55e122f.zip
Document time testing helpers
Diffstat (limited to 'guides')
-rw-r--r--guides/CHANGELOG.md3
-rw-r--r--guides/source/testing.md28
2 files changed, 31 insertions, 0 deletions
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index 09fb7b1a0e..3179746165 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,3 +1,6 @@
+* New section in Testing Guide - Testing Time Sensitive Code
+ *Gaurish Sharma*
+
* Add code of conduct to contributing guide
*Jon Moss*
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 89ae3f83e3..ea832e7176 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -1232,3 +1232,31 @@ class ProductTest < ActiveJob::TestCase
end
end
```
+
+Testing Time-Dependent Code
+---------------------------
+
+You might have code in your rails app, that is time sensitive. For example,
+you want to give some gifts to users but only after they have been a member for 1month
+which is calculated from their activation date. to test such business logic in your tests
+you will need to time travel in your tests.
+
+Fortunately, Rails provides inbuild helper methods which allow you time travel in your test code,
+allowing you assert that your time-sensitve code works as expected.
+
+Here is an example using [`travel_to`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to) helper
+
+
+```ruby
+user = User.create(name: 'Gaurish', activation_date: Date.new(2004, 10, 24))
+assert_not user.applicable_for_gifting? # `activation_date` => Wed, 24 Nov 2004
+travel_to Date.new(2004, 11, 24) do
+ assert_equal Date.new(2004, 10, 24), user.activation_date # inside the trave_to block `Date.current` is mocked
+ assert user.applicable_for_gifting? # `activation_date` => Sun, 24 Oct 2004
+end
+assert_equal Date.new(2004, 10, 24), user.activation_date # Outside the block, changed are undone
+```
+
+Please see [`ActiveSupport::TimeHelpers` API Documentation](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
+for in-depth information about the available time helpers.
+