Rails: Make this rake task aware that it is in the test environment Rails: Make this rake task aware that it is in the test environment ruby-on-rails ruby-on-rails

Rails: Make this rake task aware that it is in the test environment


I was having this problem too; in my db/seeds.rb file I have a block that creates user accounts in the development environment, but they were also being created when preparing the test environment to run rake for RSpec or Cucumber testing, which resulted in a wall of red.

Updated: I've found that the best way to specify the environment for rake tasks is to specify the environment within the task, above all statements that need the environment to be set. So in this case:

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

does the job.


From reading the db:test tasks's source, it looks like they only care about grabbing the test db info from database.yml, but don't care which actual environment they're doing it under.

You might need to run rake db:test:prepare RAILS_ENV=test to ensure you're under the test environment.