2011-07-06 24 views
2

我想在上午10點通知我的用戶他們的某個折扣是否即將到期。我正在使用heroku的每小時cron。我在Ruby 1.8.7上使用Rails 3.0.9。我有以下在lib /任務/ cron cron.rake:使用Cucumber測試重複性的cron作業

# 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' 

看來,耙不堅持過去的第一方案或需要第二個場景運行之前被重置。 ..?

謝謝...摹

回答

0
Rake::Task[].invoke 

將檢查rake任務已經調用,如果沒有執行它。即它只會執行任務一次,如果多次調用

Rake::Task[].execute 

只會在您每次調用它時執行任務。

+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 
+0

你應該[接受你自己的答案](http://blog.stackoverflow.com/2009/01/accept-your-own-answers/)。它不會增加你的聲望,但它會表明問題得到解答。 – Alex