Testing Rails migrations at GitLab
Testing Rails migrations at GitLab
为了可靠地检查 Rails 迁移,我们需要针对数据库架构对其进行测试.
- 后期迁移(
/db/post_migrate
)和后台迁移(lib/gitlab/background_migration
) 必须执行迁移测试. - 如果您的迁移是数据迁移,那么它必须具有迁移测试.
- 如有必要,其他迁移可能会进行迁移测试.
在测试签名中添加:migration
标记,可以在挂钩before
和after
运行一些自定义 RSpec.
before
钩子会将所有迁移还原到尚未迁移被测试的迁移点.
换句话说,我们的自定义 RSpec 挂钩将找到以前的迁移,并将数据库向下迁移到以前的迁移版本.
使用这种方法,您可以针对数据库架构测试迁移.
要测试ActiveRecord::Migration
类(即常规迁移db/migrate
或迁移后 ),您将需要手动require
迁移文件,因为它不会随 Rails 自动加载. 例:
table
使用table
助手为table
创建一个临时的ActiveRecord::Base
派生模型. 不应用于为迁移规范创建数据. 例如,要在projects
表中创建一条记录:
project = table(:projects).create!(id: 1, name: 'gitlab1', path: 'gitlab1')
migrate!
使用migrate!
帮助程序来运行正在测试的迁移. 它不仅将运行迁移,还将在schema_migrations
表中增加模式版本. 这是必要的,因为在after
钩中,我们会触发其余的迁移,并且我们需要知道从哪里开始. 例:
reversible_migration
Use the reversible_migration
helper to test migrations with either a change
or both up
and down
hooks. This will test that the state of the application and its data after the migration becomes reversed is the same as it was before the migration ran in the first place. The helper:
- 在向上迁移之前运行
before
期望. - Migrates up.
- Migrates down.
before
运行before
期望.
Example:
migration.before -> {
# ... pre-migration expectations
}
migration.after -> {
# ... post-migration expectations
}
end
要测试非ActiveRecord::Migration
测试(后台迁移),您将需要手动提供所需的架构版本. 请向要在其中切换数据库架构的上下文中添加schema
标签.
如果未设置,则schema
默认为:latest
.
Example:
describe SomeClass, schema: 20170608152748 do
# ...
该规范测试了lib/gitlab/background_migration/archive_legacy_traces.rb
背景迁移. 您可以在找到完整的规范
注意:由于我们使用删除数据库清除策略,因此这些测试不在数据库事务中运行. 不要依赖存在的事务.