【问题标题】:Testing a recurring cron job with Cucumber使用 Cucumber 测试重复的 cron 作业
【发布时间】:2011-08-22 20:37:12
【问题描述】:

如果他们的某个折扣即将到期,我想在上午 10 点通知我的用户。我正在使用 heroku 的每小时 cron。我在 Rails 3.0.9 和 Ruby 1.8.7 上。我在 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 似乎没有持续超过第一个场景,或者需要在第二个场景运行之前重置...?

谢谢...G

【问题讨论】:

    标签: ruby-on-rails cron cucumber


    【解决方案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
    

    【讨论】:

    【解决方案2】:
    Rake::Task[].invoke 
    

    会检查rake任务是否已经被调用,如果没有则执行。即多次调用只会执行一次任务

    Rake::Task[].execute 
    

    每次调用时都会执行该任务。

    【讨论】:

    • 感谢您的帖子。我最终这样做了:
    猜你喜欢
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2020-08-29
    • 2018-04-03
    • 2013-07-18
    • 2011-07-25
    • 1970-01-01
    • 2013-04-28
    相关资源
    最近更新 更多