我会这样做:
1) 快乐路径测试
这样的 Rake 任务测试起来很痛苦。将 rake 任务的主体提取到一个类中:
whatever.rake
desc "Import CSV file"
task :import => [:environment] do
CSVImporter.new.import "db/data.csv"
end
end
lib/csv_importer.rb
class CsvImporter
def import(data)
headers = CSV.open(data, 'r') { |csv| csv.first }
cs = headers[2..-1].map { |c| Model1.where(name: c).first_or_create }
ls = Model2.find_ls
csv_contents = CSV.read(photos)
csv_contents.shift
csv_contents.each do |row|
p = Model2.where(id: row[0], f_name: row[1]).first_or_create
p_d = FastImage.size(p.file.url(:small))
p.update_attributes(dimensions: p_d)
row[2..-1].each_with_index do |ls, i|
unless ls.nil?
ls.split(',').each { |l|
cl = Model3.where(name: l.strip, model_1_id: cs[i].id).first_or_create
Model4.where(p_id: p.id, model_3_id: cl.id).first_or_create
}
end
end
end
end
现在很容易编写一个在测试文件上调用CSVImporter.new.import 的测试(这就是import 将文件作为参数而不是硬编码的原因)并期待结果。如果在测试环境中导入db/data.csv 是合理的,您可以根据需要在测试中这样做。你可能只需要一个这样的测试。不需要存根。
2) 边缘和错误情况
这里有很多逻辑,为了简单和快速,您需要在不创建实际模型对象的情况下进行测试。也就是说,是的,你会想要存根。 Model2.find_ls 和 FastImage.size 已经很容易存根了。让我们提取一个方法来使其他模型调用易于存根:
class CsvImporter
def import(data)
headers = CSV.open(data, 'r') { |csv| csv.first }
cs = headers[2..-1].map { |c| Model1.first_or_create_with(name: c) }
ls = Model2.find_ls
csv_contents = CSV.read(photos)
csv_contents.shift
csv_contents.each do |row|
p = Model2.first_or_create_with(id: row[0], f_name: row[1])
p_d = FastImage.size(p.file.url(:small))
p.update_attributes(dimensions: p_d)
row[2..-1].each_with_index do |ls, i|
unless ls.nil?
ls.split(',').each { |l|
cl = Model3.first_or_create_with(name: l.strip, model_1_id: cs[i].id)
Model4.first_or_create_with(p_id: p.id, model_3_id: cl.id)
}
end
end
end
end
app/models/concerns/active_record_extensions.rb
module ActiveRecordExtensions
def first_or_create_with(attributes)
where(attributes).first_or_create
end
end
并将该模块包含在所有需要它的模型中。
现在可以轻松地存根所有模型方法,这样您就可以编写测试来模拟您喜欢的任何数据库情况。