Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIgrations and Rspec

I'm developing a Rails application with Rspec for unit testing.

Weeks ago, Rspec used to migrate the database to the last version automatically when executing 'rake spec', but now it doesn't do it automatically, I have to implement everything for myself.

This happens in test environment, because my development data doesn't desappear.

Is my fault? I didn't change anything, I think :)

like image 661
pablorc Avatar asked May 24 '10 15:05

pablorc


2 Answers

Typically what I do is use an alias command that runs both migrate and prepares the test database.

rake db:migrate && rake db:test:prepare

In your .bashrc just create an alias command like so and then run migrate_databases whenever you need to.

alias migrate_databases='rake db:migrate && rake db:test:prepare'
like image 188
Nick Hammond Avatar answered Nov 16 '22 19:11

Nick Hammond


My solution for Rails 4:

in spec/spec_helper.rb or anywhere in testing environment initialization code:

# Automigrate if needs migration
if ActiveRecord::Migrator.needs_migration?
  ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db/migrate'))
end

UPD: As Dorian kindly pointed out in comments, you don't need to check separately if there are any pending migrations, because ActiveRecord::Migrator.migrate already does this behind the scenes. So you can effectively use just this one line:

ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db/migrate'))
like image 11
Hnatt Avatar answered Nov 16 '22 19:11

Hnatt