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