Force Rake Task To Run in Specific Rails Environment
Solution 1
I've accomplished this kind of this before, albeit not in the most elegant of ways:
task :prepare do
system("bundle exec rake ... RAILS_ENV=development")
system("bundle exec rake ... RAILS_ENV=development")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
end
It's always worked for me. I'd be curious to know if there was a better way.
Solution 2
The way I solved it was to add a dependency to set the rails env before the task is invoked:
namespace :foo do
desc "Our custom rake task"
task :bar => ["db:test:set_test_env", :environment] do
puts "Custom rake task"
# Do whatever here...
puts Rails.env
end
end
namespace :db do
namespace :test do
desc "Custom dependency to set test environment"
task :set_test_env do # Note that we don't load the :environment task dependency
Rails.env = "test"
end
end
end
Undistraction
Updated on September 15, 2020Comments
-
Undistraction over 3 years
I need to run a series of Rake tasks from another Rake task. The first three tasks need to be run in the development environment, but the final task needs to be run in the staging environment. The task has a dependency on
:environment
which causes the Rails development environment to be loaded before the tasks run.However, I need the final task to be executed in the staging environment.
Passing a
RAILS_ENV=staging
flag before invoking the rake task is no good as the environment has already loaded at this point and all this will do is set the flag, not load the staging environment.Is there a way I can force a rake task in a specific environment?
-
Ryan Shillington about 9 yearsI couldn't use Matt Schwartz's solution above because I'm stuck on Ruby 1.8.7/Rails 2.2.2. This solution worked pretty well, actually. Ugly but simple. Thank you!
-
Neo Teo almost 8 yearshi there how can i call task :set_test_env from controller?
-
Marc-André Lafortune over 6 yearsIn Rails 4, that won't work. The main config is loaded from Rakefile, before the task is defined let alone run.