Testing cron jobs that run script/runner

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

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.