0

I have a Rails 3 gem which has some rake tasks that should only be run in the test environment. Running in other environments doesn't really make sense.

My problem is Rake loads the Rails system in order to find my tasks in my gem. So by the time it gets to my tasks Rails is already loaded in the "development" environment (or whatever environment the user specified). This means in order to run my rake tasks properly the user must do:

RAILS_ENV=test rake mytask

Since my task only make sense in the "test" environment this is annoying as I would much rather the user be able to just type:

rake mytask

This is similar to how test:units and test:functionals automatically assume the test environment and the user doesn't need to specify RAILS_ENV=test at the command line. So the question is how do I modify my test so that Rails switches to the test environment?

My current workaround is:

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

This seems to somewhat work but it is still logging to log/development.log and I think it is still actually running the "development" config. Anybody have any ideas? Looking at how the test tasks are defined in Rails itself doesn't reveal how to do it that I can see.

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

Eric Anderson
  • 3,692
  • 4
  • 31
  • 34

1 Answers1

3

UPDATE: I've updated my code after taking inputs from Eric's implementation at https://github.com/eric1234/test_inline/commit/fe3da7efa3a2cdb7824c23cfa41697b0ceb9e8e2. For original code see - 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

I didn't check for the correctness of code, but you get the idea, right?

Community
  • 1
  • 1
Vikrant Chaudhary
  • 11,089
  • 10
  • 53
  • 68
  • Genius! Simple and solves another problem I had of needing to fork to avoid one task from messing with another task. Wish I had some points so I could give you credit for a great answer. I did give you credit in the commit: https://github.com/eric1234/test_inline/commit/fe3da7efa3a2cdb7824c23cfa41697b0ceb9e8e2 – Eric Anderson Jan 29 '11 at 17:23
  • Last comment credit to Jamie Wong from http://stackoverflow.com/questions/3596431/element-update-is-not-a-function-rails-3-jquery/3611339#3611339 – Vikrant Chaudhary Feb 01 '11 at 12:46