首页 > 解决方案 > 如何在 Rails 中将输出存根到 CSV 文件而不替换/重写其中的操作?

问题描述

我正在为数据库编写代码。该数据库包含一系列用户,这些用户加入了他们参与的一系列在线会话。每个在线会话都包含开始和结束时间的属性。我的目标是将每个用户参与的总小时数加起来,并写入一个包含每个用户列表及其相关参与时间的 CSV 文件。

对于我的 RSpec 测试,我认为为每次测试运行实际创建一个 CSV 文件会很麻烦而且成本很高。我的目标是通过存根文件写入操作并使其输出到 CSV 字符串来缩短执行时间,然后我可以在我的测试文件中读取它(因为测试将只包含一两行,而不是可能数百行就像在生产中一样)。以下是辅助函数的相关部分:

def write_to_csv(file, table, headers)
  hours_worked = 0
  current_tutor = ''
  CSV.open(file, 'w', write_headers: true, headers: headers) do |writer|
    table_iterate(table, writer, hours_worked, current_tutor)
  end
end

def table_iterate(table, writer, hours_worked = 0, current_tutor = '')
  table.each do |entry|
    # Switch currently tracking tutor and print last one
    if current_tutor != full_name(entry)
      writer << [current_tutor, hours_worked.to_s] if current_tutor != ''
      current_tutor = full_name(entry)
      hours_worked = 0
    end
    # Update hours_worked
    hours_worked += entry_duration(entry)
  end
end

我想将所有内容输出到 CSV 字符串而不是文件,但我仍然希望下面的所有内容table.each do |entry|完全按照原本的方式发生。我的第一次尝试是让我的 RSpec 包含代码

allow(CSV).to receive(:<<) do |args1|
  csv_string = [args1[0], args1[1]].to_csv
end

但后来我得到了一个错误,“CSV 没有收到 <<”。我也试过allow(File).to receive(:open) {csv_string = CSV.generate}了,但我很确定这会覆盖 table_iterate 函数,而且我得到了错误

LocalJumpError:
       no block given (yield)

有任何想法吗?我对它需要是一个 CSV 字符串并不是非常严格,只要我可以最大限度地减少从文件读取/写入的时间成本。

标签: ruby-on-railscsvrspec-rails

解决方案


推荐阅读