# Testing cron jobs that run script/runner

**URL:** <https://www.ruby-forum.com/t/testing-cron-jobs-that-run-script-runner/112965>\
**Category:** Rails\
**Created:** [August 25, 2007, 12:57am UTC](https://www.ruby-forum.com/t/testing-cron-jobs-that-run-script-runner/112965 "2007-08-25T00:57:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![helzer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/e19b73/32.png) [@helzer](https://www.ruby-forum.com/u/helzer)\
**Post date:** [August 25, 2007, 12:57am UTC](https://www.ruby-forum.com/t/testing-cron-jobs-that-run-script-runner/112965/1 "2007-08-25T00:57:01Z")

</div>

I’ve got some logic that runs periodically and I want to include that  
in my tests.

I guess, the test will need to modify the Time.now(), so that I can  
trigger events to happen and also run some code, in the same way  
script/runner would do.

Any suggestions?

Thanks,  
Amir

---

<div class="post-metadata">

**Author:** ![helzer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/e19b73/32.png) [@helzer](https://www.ruby-forum.com/u/helzer)\
**Post date:** [August 25, 2007, 4:03am UTC](https://www.ruby-forum.com/t/testing-cron-jobs-that-run-script-runner/112965/2 "2007-08-25T04:03:20Z")

</div>

helzer wrote:

> I’ve got some logic that runs periodically and I want to include that  
> in my tests.

The closer to the cron event you get, the harder the testing is. Which  
do  
you want to test?

- the cron system works
- the cron file calls your function, not something else
- your function works.

The last one is highest risk, and you can test that out of normal unit  
tests. So most crons should let the first two slide.

> I guess, the test will need to modify the Time.now(), so that I can  
> trigger events to happen and also run some code, in the same way  
> script/runner would do.

I have experienced two general ways to mock the time. One is to mock  
Time.now() so it returns some canned number that the time-dependent code  
will relate to.

The other way is to set a previous time stamp wisely in the test  
fixtures. A  
contrived example for an hourly cron:

due\_for\_a\_cron:  
id: 42  
data: whatever  
last\_cron: \<%= 61.minutes.ago %\>

So a test case that uses a :due\_for\_a\_cron fixture record will always  
correctly discover that the time is ripe for the next cron event.

I have found the fixture system to be much more robust than mocking  
Time. If  
you simply must do that, use Mocha.

–  
Phlip  
[http://www.oreilly.com/catalog/9780596510657/](http://www.oreilly.com/catalog/9780596510657/)
