我想在上午10点通知我的用户,如果其中一个折扣即将到期。我正在使用heroku的每小时cron。我使用Ruby 1.8.7在Rails 3.0.9上。我在lib / tasks / cron中有以下cron.rake:
# Notify users with expiring claims
puts "Notifying users with expiring claims..."
if Time.zone.now.hour == 10
Claim.expiring_tomorrow.reject(&:redeemed?).compact.each do |claim|
Mailer.delay.notify_customer_claim_expiration(claim)
claim.update_attribute(:expiration_notified, true)
end
end
puts "done."
这很有效。我的问题是我必须在黄瓜中测试三种不同的场景:
Scenario: Not receiving a expiration reminder too early
Scenario: Receiving a expiration reminder only once
Scenario: Not receiving a reminder for a redeemed claim
所以我写了以下功能:
Feature: Being reminded that a claimed discount is expiring
Background:
Given the hourly cron job exists
Scenario: Not receiving a expiration reminder too early
And the hourly cron job has fired
Scenario: Receiving a expiration reminder only once
And the hourly cron job has fired
Scenario: Not receiving a reminder for a redeemed claim
And the hourly cron job has fired
使用以下cron.steps步骤定义:
And /^the hourly cron job exists$/ do
require "rake"
@rake = Rake::Application.new
Rake.application = @rake
Rake.application.rake_require "lib/tasks/cron"
end
And /^the hourly cron job has fired$/ do
Rake::Task["cron"].invoke
end
如果我单独运行每个场景,它们会通过。如果我运行整个功能,它会在第二个(不是第一个)场景中失败:
RuntimeError: Don't know how to build task 'cron'
似乎Rake没有持续超过第一个场景,或者需要在第二个场景运行之前重置......?
...谢谢ģ
答案 0 :(得分:1)
感谢您的帖子。我最终这样做了:
And /^a cron job exists$/ do
require "rake"
@rake = Rake::Application.new
Rake.application = @rake
# remove cron.rake from list of required files to force file to be reloaded
loaded = $".reject {|file| file == Rails.root.join("lib", "tasks", "cron.rake").to_s }
Rake.application.rake_require("lib/tasks/cron", [Rails.root.to_s], loaded)
Rake::Task.define_task(:environment)
end
And /^the hourly cron job has fired$/ do
@rake["cron"].invoke
end
答案 1 :(得分:0)
Rake::Task[].invoke
将检查是否已经调用了rake任务,如果没有,则执行它。即,如果多次调用,它将只执行一次任务
Rake::Task[].execute
每次调用它时,都会执行任务。