WowBow
WowBow

Reputation: 7593

Need help migrating database from development to test using Rails

Similar questions has been asked a lot. But, I think my situation is a bit different. I pulled a db from Heroku (I use sqlite3 in prod) to my local machine (uses PostgreSQL ). The prod db didn't have any data at that time.

After that time I haven't done any db migrations to test. Now I have a couple of fields in my dev db. However, when I go to test console to see what I have (referring a User table) User.count returns 0, but returns 2 users in dev.

So I did rake db:migrate RAILS_ENV=test there was neither an error message nor a success message. I thought it was success and checked the test db if it has those 2 users and still nothing. Then I tried bundle exec rake db:test:prepare. This was the output

**You have 4 pending migrations:

  20120415210441 CreateUsers

  20120418064930 AddIndexToUsersEmail

  20120419034627 AddPasswordDigestToUsers

  20120504031144 AddRememberTokenToUsers

Run `rake db:migrate` to update your database then try again.**

What is the solution?

EDIT: FYI: I am using windows I also run rake db:migrate and I got this error.

$ rake db:migrate
==  CreateUsers: migrating ====================================================
-- create_table(:users)
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id"
INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varcha
(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Upvotes: 2

Views: 3458

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10089

The error message indicates that your dev and test migrations are out of sync.

First run migrate on dev. This will update dev with all your recent migrations.

rake db:migrate

Then run db:test:prepare. This will make the test database the same schema as dev.

rake db:test:prepare

Now, understand that db:test:prepare makes test have the same schema as dev, but with no records. To populate records in test, implement fixtures or factories (see the factory-girl gem). Factories are generally called in your test to create records for that test.

Upvotes: 7

Marlin Pierce
Marlin Pierce

Reputation: 10089

That's another question and another answer.

You should drop the table and re-run the migrations.

If you don't know how to drop a table in SQLite, then

  1. comment out the create_table method call in the 20120415210441_CreateUsers.rb.
  2. Run > rake db:migrate VERSION=20120415210441
  3. Run > rake db:migrate VERSION=??? where ??? is the version of the migration prior to CreateUsers.
  4. Uncomment the code in 20120415210441_CreateUsers.rb
  5. Run > rake db:migrate

Upvotes: 1

Related Questions