gpt4 book ai didi

ruby-on-rails - 用于 CSV 上传的 Rspec

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:35 25 4
gpt4 key购买 nike

我有一个实现从服务上传 csv 的代码。

 require 'csv'

class ActualCsvProjectUpdater
def self.import(file, project)
CSV.foreach(file.path, headers: true) do |row|
actual_billable_hours, actual_non_billable_hours, start_date = row['actual_billable_hours'], row['actual_non_billable_hours'], row['start_date']


week = project.weeks.find_by(start_date: start_date)

if week.present?
week.update!(actual_billable_hours: row['actual_billable_hours'], actual_non_billable_hours: row['actual_non_billable_hours'])
end
end
end
end`

我如何为此编写测试?

最佳答案

我首先将夹具文件放在 ./spec/fixtures/*.csv 中(如果需要,可能放在子文件夹中)。例如,像这样的东西:

actual_billable_hours,actual_non_billable_hours,start_date
12,4,2017-10-20
6,7,2017-10-04

在您的spec 中,您需要初始化一些Project(s) 和Week(s);然后用这个夹具文件调用方法。类似的东西:

Rspec.describe 'ActualCsvProjectUpdater' do
describe '.import' do
let!(:project) { create :project, weeks: [week1, week2] }
let(:week1) { create :week, ... }
let(:week2) { create :week, ... }
let(:csv_file) { File.new(fixture_path + '/csv/project_billable_hours.csv') }

it 'updates week included in file' do
descibed_class.import(csv_file, project)
expect(week1.reload.actual_billable_hours).to eq 12
expect(week1.reload.actual_non_billable_hours).to eq 4
end
end
end

当然,这只是一个指南。例如,我假设您使用的是 factory_girl,但这不是必需的。

希望这能为您指明正确的方向 - 您还将受益于添加更多测试以涵盖边缘情况。 (如果日期是 future 的?或遥远的过去?或日期无效?或计费时间为负数/空白/不是数字怎么办?如果 csv 文件包含错误的标题怎么办?如果文件是 庞大,并导致性能问题?为您的应用程序需要考虑的任何内容添加测试。)

关于ruby-on-rails - 用于 CSV 上传的 Rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com