Automatically run gem tasks in test environment

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.


UPDATE: I've updated my code after taking inputs from Eric's implementation at For original code see -

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"
    #.... stuff ....

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

Need Your Help

Java: Casting rule for hierarchy inhertance

java casting

As picture shown, I have an hierarchy of inherited classes. I am looking for a general rule as up to down or down to up rules.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.