Home > Software design >  Run tests located in a Rails Engine when mounted in host application
Run tests located in a Rails Engine when mounted in host application

Time:04-14

I have some tests located in an engine called "Blorgh". I simply test my engine by running the following command in the root directory of my engine's repository.

rails test
...
19 runs, 8 assertions, 0 failures, 0 errors, 11 skips

Simple. Now, Blorgh is mounted in an app.

gem blorgh

This app is deployed using a pipeline that includes a test step. I want the test step to execute the mounted engine's tests so that the pipeline stops deployment if it finds a problem with the tests in the Blorgh engine.

The problem is that when rails test is executed in the root directory of the host app, it only looks for tests specific to the host app.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

How can I execute the tests for my Blorgh engine when it is mounted? I've searched high and low. I'm willing to make my own task by crawling Blorgh::Engine.root, but I'm not even sure what rails test is doing under the hood.

CodePudding user response:

If you have to you can set up a rake task to load just the tests you need. Main app "test" directory should be in your load path, because test/test_helper.rb loads the environment.

# lib/tasks/run_engine_tests.rake

task :run_engine_tests do
  # Add main app `test` directory to load path
  # This means requires such as `require "test_helper"` will load main app 
  #   helper instead of engine helper. That's what we need to run the tests
  #   under our app, because engine's `test_helper.rb` loads dummy app.
  $LOAD_PATH << Rails.root.join("test").to_s

  # require tests from the engine that you need to run
  Dir.glob(Blorgh::Engine.root.join("test/**/*_test.rb")).each { |f| require f }
  
  # rails magic does the rest
  require "active_support/testing/autorun"
end

and do a quick test

$ RAILS_ENV=test bin/rails run_engine_tests
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 12153

# Running:

hello from Blorgh
.

Finished in 0.004990s, 200.4139 runs/s, 200.4139 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

Use RAILS_ENV=test otherwise it's loading test environment twice.

For reference, take a look at these

https://github.com/rails/rails/blob/v7.0.2.3/railties/lib/rails/commands/test/test_command.rb#L29

https://github.com/rails/rails/blob/v7.0.2.3/railties/lib/rails/test_unit/runner.rb#L39

  • Related