In my Rails 6 app I want to write MiniTest for a service which is responsible for creating CSV files. I found few examples (like here) of how to do it when the services responsible for it use CSV.open
instead of CSV.generate
like mine. I've below code:
# 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|
tracked_data(v)
csv << [v.created_at.in_time_zone('London'),
v.event,
user_name(v),
@new_data_value]
end
end
end
# csv_log_generator_test
class CsvLogGeneratorTest < ActiveSupport::TestCase
setup do
Book.create!(title: 'title')
service.call
end
test 'something that needs versioning' do
with_versioning do
expected_csv = File.open(file_fixture('sample.csv')).read
assert_equal expected_csv
end
end
I don't know how to get this newly created CSV file from a service.call
so that I can compare it with expected_data inside assert_equal
.
CodePudding user response:
Your service (I assume the service is CsvLogGenerator
itself returns a string, so your test should read something like this (except I have omitted the apparently irrelevant with_versioning
wrapper block)
class CsvLogGeneratorTest < ActiveSupport::TestCase
setup do
Book.create!(title: 'title')
end
test 'something that needs versioning' do
service = CsvLogGenerator.new
actual_csv = service.call
expected_csv = File.open(file_fixture('sample.csv')).read
assert_equal expected_csv, actual_csv
end
end