【问题标题】:`bundle exec rake` or `rake`? What about `Rake::TestTask`?`bundle exec rake` 还是 `rake`? `Rake::TestTask` 呢?
【发布时间】:2014-06-22 14:21:39
【问题描述】:

打电话给bundle exec rakebundle exec make 在我看来很奇怪:为什么不呢

bundle exec bundle exec rake

然后呢?

虽然我应该能够从 Rakefile(或 Makefile)中要求和使用 Bundler。但是,我找不到如何使用正确的宝石组运行测试,以下不起作用:

# Rakefile
require 'rake/testtask'

Rake::TestTask.new do |t|
  require 'bundler'
  Bundler.setup(:default, :test)  # this has no effect
  t.test_files = FileList['test.rb']
end

有人可以帮助我正确设置 Rake 测试任务,或者解释使用 bundle exec rake 的哲学原因吗?

注意bundle exec rake 需要将gem rake 添加到 Gemfile。

【问题讨论】:

    标签: ruby testing rake bundler rake-task


    【解决方案1】:

    bundle exec 的全部目的是在项目的Gemfile 上下文中运行以下任何内容。

    没有它,对rake 的调用可能会使用系统范围内安装的 rake 和/或 gem。这不允许对每个项目中使用的每个 gem 的哪个版本进行细粒度控制。当您开发(或在生产环境中提供服务)多个使用相同 gem 的不同版本的 ruby​​ 项目时,这一点变得尤为重要。

    Bundler 允许您的项目是自包含的,而无需对系统可用依赖项进行任何假设。

    话虽如此,您可以创建一个 shell 别名,用 bundle exec 作为前缀。例如,我的 zsh 配置(启用了 bundler 插件)为我提供了 be 的简写 bundle exec

    【讨论】:

    • 是的,我知道这一点,但为什么 Rakefile(或 Makefile,如果我使用的是 GNU Make 而不是 Rake)不能解决这个问题?我没有听说过运行make,例如,通过另一个命令。
    • 因为他们没有假设您实际上正在使用捆绑程序。 bundler 很有用且有时必不可少,您可以选择在没有它的情况下运行 ruby​​ 项目。
    • 为什么我可以假设我正在使用 Rake(通过在 Gemfile 中包含 gem rake),但不能假设我正在使用 Bundler?如果我选择使用 Bundler,为什么不在 Rakefile 或 Makefile 中自动化它?
    • Rakefile 是一个独立文件,每次发出rake 命令时都会获取该文件。这不需要您为此使用 bundle 或其他任何东西。如果您决定使用 bundle 来处理您的依赖关系,那么使用bundle exec ... 是有意义的。 Rake(和 Rakefile)仍然与 bundler 无关。这意味着我可以发出一个rake 命令,它会在没有安装bundler gem 的情况下咨询Rakefile
    • 如果我想让 Rake 任务始终使用捆绑的 gem,以及其他不依赖于 bundler 并可能使用系统 gem 或可执行文件的任务,那么我需要始终使用 @987654336 调用一些任务@ 和一些总是没有。
    【解决方案2】:

    关于 Bundler.setup(:default, :test) 无效,在我看来这可能是由 Bundler 错误引起的,例如 this one

    我认为这是一个错误,因为 Bundler.setup 并没有真正被忽略。

    考虑以下设置:

    # Gemfile
    source 'https://rubygems.org'
    ruby '2.1.1'
    gem 'rack-test', :group => :test
    
    # Rakefile
    require 'rake/testtask'
    Rake::TestTask.new do |t|
      require 'bundler'
      Bundler.setup(:default)
      t.test_files = FileList['test.rb']
    end
    
    # test.rb
    require 'bundler'
    Bundler.setup(:default)
    require 'rack/test'
    

    出乎意料,rake test 运行没有错误。

    如果我在 Rakefile 中注释掉 Bundler.setup(:default),则它不再需要 rack/test。

    【讨论】:

    • bug 已修复,但我尚未尝试查看 Bundler.setup(:default, :test) 现在是否可以使用。
    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2012-05-28
    • 2015-05-25
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多