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
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With