Search code examples
ruby-on-railsruby-on-rails-3testingrails-migrations

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)

Solution

  • 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.