【发布时间】:2016-05-20 03:43:09
【问题描述】:
我想测试我的迁移文件。有两个表:位置和用户。位置 has_many 用户。表通过 location_id 连接。迁移是向“位置”表中的“名称”列添加唯一约束,并删除“位置”表中具有重复位置名称的重复行,并使所有用户指向其位置的第一次出现。
这是我的迁移文件的一部分:
def self.remove_duplications
grouped = all.group_by{|location| [location.name] }
grouped.values.each do |duplicates|
# the first one we want to keep right?
first_one = duplicates.shift # or pop for last one
users = User.all
users.each do |user|
if user.location && user.location.name == first_one.name
user.location_id = first_one.id
user.save!
end
end
duplicates.each do |duplicate|
duplicate.destroy!
end
end
end
end
def self.up
Location.remove_duplications
remove_index :locations, column: :name
add_index :locations, :name, unique: true
end
def self.down
remove_index :locations, column: :name # remove unique index
add_index :locations, :name # adds just index, without unique
end
我该如何测试呢?手动测试它变得越来越困难。
【问题讨论】:
-
我见过这个,但它使用 Rspec 进行测试。但我没有使用 Rspec。还有其他建议吗?
标签: ruby-on-rails unit-testing migration