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'))