Peter Marklund具有测试的一个例子要旨这里的迁移:https://gist.github.com/700194(在rspec中)。
注意迁移自他的示例使用实例方法而不是类方法以来已更改。
这里有一个总结:
- 创建迁移照常
- 创建一个文件,把你的迁移测试中建议:
test/unit/import_legacy_devices_migration_test.rb
或spec/migrations/import_legacy_devices_migration_spec.rb
注意:您可能需要显式地加载迁移文件轨道可能不会为你加载。像这样的东西应该做的:require File.join(Rails.root, 'db', 'migrate', '20101110154036_import_legacy_devices')
- 迁移是(像红宝石一切),就是一个类。测试
up
和down
方法。如果你的逻辑很复杂,我建议将一些逻辑重构成较小的方法,这样更容易测试。
- 调用
up
,设置一些一些数据,因为这将是您的迁移之前,并断言它的状态,你的期望之后之前。
我希望这会有所帮助。
UPDATE:自发布此消息以来,我在我的博客上发布了example migration test。
UPDATE:这里有一个想法,即使在开发中运行它们之后,仍然可以测试迁移。
编辑:我已将我的概念证明更新为完整的spec文件,使用我博客文章中的人为示例。
# spec/migrations/add_email_at_utc_hour_to_users_spec.rb
require 'spec_helper'
migration_file_name = Dir[Rails.root.join('db/migrate/*_add_email_at_utc_hour_to_users.rb')].first
require migration_file_name
describe AddEmailAtUtcHourToUsers do
# This is clearly not very safe or pretty code, and there may be a
# rails api that handles this. I am just going for a proof of concept here.
def migration_has_been_run?(version)
table_name = ActiveRecord::Migrator.schema_migrations_table_name
query = "SELECT version FROM %s WHERE version = '%s'" % [table_name, version]
ActiveRecord::Base.connection.execute(query).any?
end
let(:migration) { AddEmailAtUtcHourToUsers.new }
before do
# You could hard-code the migration number, or find it from the filename...
if migration_has_been_run?('20120425063641')
# If this migration has already been in our current database, run down first
migration.down
end
end
describe '#up' do
before { migration.up; User.reset_column_information }
it 'adds the email_at_utc_hour column' do
User.columns_hash.should have_key('email_at_utc_hour')
end
end
end
非常好的问题。 +1 – d11wtq 2011-05-21 02:22:51
这看起来像一个有用的帖子:http://blog.carbonfive.com/2011/01/27/start-testing-your-migrations-right-now/ – maahd 2016-02-12 14:57:11