简体   繁体   中英

Running RSpec for Rails project from within sub-project

I am writing a command line tool (using thor) for my Rails project that is supposed to retrieve a list of specs to run and then run them. However, this tool is in a subdirectory within my Rails project with its own Gemfile. The directory structure looks like this:

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

The command in commands.rb calls the function:

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

rails_project obviously has Rails in its Gemfile but command_line_tool does not, so when I run specs_command in commands.rb , it fails with the error LoadError: cannot load such file -- rails because it's trying to run RSpec specs in its parent directory. Is there a way to force RSpec to use the Rails dependency of another project? I would like to be able to do this without adding Rails as a dependency to my command line tool.

I don't think there's a way to get RSpec, or even bundler, to somehow use a different set of gems in the same Ruby process. You could probably figure out how to get bundler to load a second Gemfile full of gems in the same Ruby process, but that would eventually cause problems when your command-line tool and your Rails app needed mutually incompatible gems. ( Something like this has happened to me. )

Instead, just run the rspec command with system (or one of the many other ways to run executables that Ruby provides):

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

system 's return value (ie rspec's exit status) will tell you if the tests passed or failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM