开发者

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 di开发者_如何学运维dn't change anything, I think :)


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'


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


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're good to go. More info here.


Here's 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 default task doesn't default to run_specs


See if you have the following in your spec_helper.rb? Everytime you run specs, RSpec checks 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)


This works even when Rails is not loaded and only does one SQL query most of the time.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜