How do I force RAILS_ENV in a rake task?

后端 未结 6 903
暗喜
暗喜 2020-11-28 06:00

I have this little rake task:

namespace :db do 
  namespace :test do 
    task :reset do 
      ENV[\'RAILS_ENV\'] = \"test\" 
      Rake::Task[\'db:drop\']         


        
6条回答
  •  猫巷女王i
    2020-11-28 06:34

    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)
    

提交回复
热议问题