MIgrations and Rspec

I am developing a Rails application with Rspec for unit testing.

A few weeks ago, Rspec used to transfer the database to the latest version automatically when doing the "rake spec", but now it does not do it automatically, I have to implement everything for myself.

This happens in a test environment because my development data does not disappear.

It's my fault? I didn’t change anything, I think :)

Thanks in advance.

+7
ruby-on-rails rspec
source share
6 answers

Usually I use the alias command, which starts both the migration and preparation of the test database.

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

In your .bashrc, just create such an alias command and then run migrate_databases when you need to.

 alias migrate_databases='rake db:migrate && rake db:test:prepare' 
+14
source share

My solution for Rails 4:

in spec/spec_helper.rb or anywhere in the test 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 the comments, you do not need to separately check if there are pending migrations, because ActiveRecord::Migrator.migrate already doing this behind the scenes. Thus, you can effectively use only one line:

 ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db/migrate')) 
+7
source share

Rails 4.1 forward you can use:

 ActiveRecord::Migration.maintain_test_schema! 

Add at the top of your spec_helper.rb or rails_helper.rb and you will go well. More info here .

+5
source share

Here is my workaround:

Rakefile:

 require File.expand_path('../config/application', __FILE__) require 'rake' require "rspec/core/rake_task" MyApp::Application.load_tasks desc "Run specs" RSpec::Core::RakeTask.new(:spec) task :run_specs => ['db:test:clone', :spec] do end task :default => :run_specs 

Then I run $ rake run_specs

for some reason the default task does not start run_specs

+1
source share

See if your spec_helper.rb has the following: Each time you run the specs, RSpec checks to see if there are pending migrations.

 #Checks for pending migrations before tests are run. #If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration) 
0
source share

This works even when Rails does not load and only one SQL query takes up most of the time.

 if defined?(ActiveRecord::Migrator) ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db', 'migrate')) end 
0
source share

All Articles