【问题标题】:Running RSpec for Rails project from within sub-project从子项目中运行 RSpec for Rails 项目
【发布时间】:2016-06-01 15:10:15
【问题描述】:

我正在为我的 Rails 项目编写一个命令行工具(使用 thor),它应该检索要运行的规范列表,然后运行它们。然而,这个工具在我的 Rails 项目的一个子目录中,它有自己的 Gemfile。目录结构如下:

- rails_project
  - Gemfile
  - command_line_tool
    - commands.rb
    - Gemfile

commands.rb中的命令调用函数:

def specs_command
  specs_to_run = get_specs_to_run()
  RSpec::Core::Runner.run(specs_to_run)
end

rails_project 显然在其Gemfile 中有Rails,但command_line_tool 没有,所以当我在commands.rb 中运行specs_command 时,它会因错误LoadError: cannot load such file -- rails 而失败,因为它试图在其中运行RSpec 规范父目录。有没有办法强制 RSpec 使用另一个项目的 Rails 依赖项?我希望能够在不将 Rails 作为依赖项添加到我的命令行工具的情况下做到这一点。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rspec thor


    【解决方案1】:

    我认为没有办法让 RSpec 甚至捆绑器以某种方式在同一个 Ruby 进程中使用一组不同的 gem。您可能会想出如何让捆绑器在同一个 Ruby 进程中加载​​一个 second Gemfile 充满 gem,但是当您的命令行工具和 Rails 应用程序需要相互不兼容的 gem 时,这最终会导致问题. (Something like this has happened to me.)

    相反,只需使用 system 运行 rspec 命令(或 Ruby 提供的许多其他运行可执行文件的方法之一):

    system "bundle exec rspec #{specs_to_run.join(' ')}",
      chdir: File.expand_path(File.dirname($PROGRAM_NAME) + '/..')
    

    system 的返回值(即 rspec 的退出状态)会告诉您测试是通过还是失败。

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2016-09-03
      • 2022-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多