Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following rake task defined in my lib/tasks folder:

namespace :db do
  namespace :test do
    task :prepare => :environment do
      Rake::Task["db:seed"].invoke
    end
  end
end

Now, what this does is seed the test DB when I run rake db:test:prepare. I do this because I have some basic records that must exist in order for the app to function, so they're not optional and can't really be mocked.

Separately, I have a model that uses S3 for asset storage in development and production, but I don't want it to use S3 for testing. I have set up a method in the model that changes the storage path from S3 to local if Rails.env.test?

However, this isn't working. I was wondering if the rake task was aware of what environment it was being called from, and it turns out it is NOT. I put this at the top of my seeds.rb file:

puts "Environment Check: Rails Environment = #{Rails.env}"

Sure enough, when the task runs this prints: Environment Check: Rails Environment = development

So, how can I redo this rake task so that when it's seeding the test DB it knows that it's seeding the test DB??

like image 681
Andrew Avatar asked Apr 02 '11 20:04

Andrew


People also ask

How to make rake task in Rails?

If you want to write your own rake task you have 2 ways to do it (I thought so before): Write it from scratch. Copy-paste code from another ready rake task and change code to required.

What are rake tasks in Rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

Where is rake task?

Summary. You have learned about Rake, a popular task runner for Ruby. Use rake -T to find out what tasks are available, create your own tasks & add them to the Rakefile , or inside the lib/tasks folder, and remember that Rake & Rack are different things.


1 Answers

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.

like image 97
jbhannah Avatar answered Sep 18 '22 06:09

jbhannah