I have this little rake task:
namespace :db do
namespace :test do
task :reset do
ENV[\'RAILS_ENV\'] = \"test\"
Rake::Task[\'db:drop\']
The cleanest and simplest solution would be to redefine RAILS_ENV (not ENV['RAILS_ENV'])
namespace :db do
namespace :test do
task :reset do
RAILS_ENV = "test"
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
Rake::Task['db:migrate'].invoke
end
end
end
During the boot process of a Rails application RAILS_ENV is initialized as follows
RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV)
The rest of Rails code uses RAILS_ENV directly.
However, as Michael has pointed out in a comment to his answer, switching RAILS_ENV on the fly can be risky. Another approach would be to switch the database connection, this solution is in fact used by the default db:test tasks
ActiveRecord::Base.establish_connection(:test)