【问题标题】:Automatically run gem tasks in test environment在测试环境中自动运行 gem 任务
【发布时间】:2010-12-03 21:11:50
【问题描述】:

我有一个 Rails 3 gem,它有一些只能在测试环境中运行的 rake 任务。在其他环境中运行并没有什么意义。

我的问题是 Rake 加载 Rails 系统以便在我的 gem 中找到我的任务。因此,当它执行我的任务时,Rails 已经加载到“开发”环境(或用户指定的任何环境)中。这意味着为了正确运行我的 rake 任务,用户必须这样做:

RAILS_ENV=test rake mytask

由于我的任务仅在“测试”环境中才有意义,这很烦人,因为我更希望用户能够输入:

rake mytask

这类似于 test:units 和 test:functionals 自动假定测试环境的方式,用户无需在命令行中指定 RAILS_ENV=test。那么问题是如何修改我的测试,让 Rails 切换到测试环境?

我目前的解决方法是:

Rails.env = 'test'
ActionMailer::Base.delivery_method = :test
require Rails.root.join('test/test_helper')

这似乎有点工作,但它仍在记录到 log/development.log,我认为它实际上仍在运行“开发”配置。有人有什么想法吗?查看 Rails 本身如何定义测试任务并不能揭示我所看到的如何去做。

https://github.com/rails/rails/blob/master/railties/lib/rails/test_unit/testing.rake

【问题讨论】:

    标签: testing ruby-on-rails-3 rake gem environment


    【解决方案1】:

    更新:在从 Eric 在https://github.com/eric1234/test_inline/commit/fe3da7efa3a2cdb7824c23cfa41697b0ceb9e8e2 的实现中获取输入后,我更新了我的代码。 原始代码见-https://stackoverflow.com/posts/4600524/revisions

    desc "Do something in Test environment"
    task :example => :environment do
      if not Rails.env.test?
        Dir.chdir(Rails.root) do
          system "rake example RAILS_ENV=test"
        end
      else
        #.... stuff ....
      end
    end
    

    我没有检查代码的正确性,但你明白了吧?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多