Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force RAILS_ENV in a rake task?

I have this little rake task:

namespace :db do    namespace :test do      task :reset do        ENV['RAILS_ENV'] = "test"        Rake::Task['db:drop'].invoke       Rake::Task['db:create'].invoke       Rake::Task['db:migrate'].invoke     end   end end 

Now, when I execute, it will ignore the RAILS_ENV I tried to hard-code. How do I make this task work as expected

like image 285
Sam Saffron Avatar asked Jul 07 '09 03:07

Sam Saffron


People also ask

What is environment rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.


2 Answers

For this particular task, you only need to change the DB connection, so as Adam pointed out, you can do this:

namespace :db do    namespace :test do      task :reset do        ActiveRecord::Base.establish_connection('test')       Rake::Task['db:drop'].invoke       Rake::Task['db:create'].invoke       Rake::Task['db:migrate'].invoke       ActiveRecord::Base.establish_connection(ENV['RAILS_ENV'])  #Make sure you don't have side-effects!     end   end end 

If your task is more complicated, and you need other aspects of ENV, you are safest spawning a new rake process:

namespace :db do    namespace :test do      task :reset do        system("rake db:drop RAILS_ENV=test")       system("rake db:create RAILS_ENV=test")       system("rake db:migrate RAILS_ENV=test")     end   end end 

or

namespace :db do    namespace :test do      task :reset do        if (ENV['RAILS_ENV'] == "test")         Rake::Task['db:drop'].invoke         Rake::Task['db:create'].invoke         Rake::Task['db:migrate'].invoke       else         system("rake db:test:reset RAILS_ENV=test")       end     end   end end 
like image 197
Michael Sofaer Avatar answered Sep 21 '22 03:09

Michael Sofaer


In Rails 3, you'll have to use

Rails.env = "test" Rake::Task["db:drop"].invoke 

instead of

RAILS_ENV = "test" Rake::Task["db:drop"].invoke  
like image 29
yacc Avatar answered Sep 19 '22 03:09

yacc