在我的 Rails 6 應用程式中,我想為一個負責創建 CSV 檔案的服務撰寫 MiniTest。我找到了一些例子(比如這里),說明當負責的服務使用CSV.open而不是像我這樣使用CSV.generate時如何做。我有下面的代碼:
# services/csv_log_generator。
class CsvLogGenerator
LOG_HEADERS = ['Created at', 'Action Type', 'Acting User', 'New Data'].freeze
def call>>。
CSV。 generate(col_sep: '; ', write_headers: true, headers: LOG_HEADERS, encoding: 'UTF-8') do|csv|
PaperTrail::Version.includes([:item]).where(item_type: 'CashTransaction') 。 limit(99).order(id: :desc).each do |v|
追蹤的資料(v)
csv << [v.created_at.in_time_zone('London') 。
v.事件。
user_name(v),
@new_data_value]
end
end
end end
# csv_log_generator_test
class CsvLogGeneratorTest < ActiveSupport::TestCase
設定do
Book.create! (title: 'title')
service.call
結束。
測驗 '需要版本管理的東西' do
with_versioningdo
expected_csv = File.open(file_fixture('sample.csv')).read
assert_equal expected_csv
結束。
結束。
我不知道如何從service.call中獲得這個新創建的CSV檔案,以便我可以在assert_equal中將其與預期資料進行比較。
uj5u.com熱心網友回復:
你的服務(我假設服務是CsvLogGenerator本身回傳一個字串,所以你的測驗應該是這樣的(除了我省略了明顯無關的with_versioning封裝塊)
class CsvLogGeneratorTest < ActiveSupport::TestCase
設定do
Book.create! (title: 'title')
結束。
測驗 '需要版本的東西' do
service = CsvLogGenerator.new
actual_csv = service.call
expected_csv = File.open(file_fixture('sample.csv')).read
assert_equal expected_csv, actual_csv
結束。
結束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322752.html
標籤:
