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.

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

Answers


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 - http://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?


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.