sguha
sguha

Reputation: 2197

Running db:test:prepare in Rake task throws off environment

I have the following 2 rake tasks:

task :clone => :environment do |t, args|
  Rake::Task["db:drop"].invoke 
  Rake::Task["db:create"].invoke
  system "pg_restore -O -d database_name last_dump"
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:test:prepare"].invoke

  # Try to force the rails env to reload, but this doesn't solve the problem
  Rake::Task["environment"].execute
  Rake::Task["db:company_count"].invoke
end

task :company_count => :environment do
  puts Company.count
end

When I run rake db:clone the output the Company.count is 0 indicating there are no Companies in the database, but when I run rake db:clone && rake db:company_count the output is 2.

How do I get the correct Company.count after loading the database in the first task?

The Company.count is correct if I remove Rake::Task["db:test:prepare"].invoke from the clone task, but I'm not sure why

Upvotes: 0

Views: 287

Answers (2)

Andy Gauge
Andy Gauge

Reputation: 1428

guides.rubyonrails.org indicates that the task db:test:prepare is used to do the following to your test database:

  1. drop the database
  2. create the database
  3. run the migrations

After this task completes, you will not have any data in there. Here are stack overflow answers that explains this:

  1. PG undefinedtable error relation users does not exist
  2. What does rake db:test:prepare actually do

I believe the behavior you are seeing has nothing to do with the environment, but a misunderstanding in the intention of this rake task.

Upvotes: 1

penner
penner

Reputation: 2737

My guess is first task is not using the console environment because it creates its own terminal session for the rake, and the second one is.

Try printenv and compare the variables

Also try prefixing the commands with RAILS_ENV=development or whatever environment you want.

Upvotes: 1

Related Questions