Skip to content

Instantly share code, notes, and snippets.

@westonganger
Created August 31, 2021 03:58
Show Gist options
  • Save westonganger/49de83c31d9af9ca4112960fcbca0627 to your computer and use it in GitHub Desktop.
Save westonganger/49de83c31d9af9ca4112960fcbca0627 to your computer and use it in GitHub Desktop.
Rails Test/Spec File Helpers
def create_tempfile(str_data, file_name: nil)
file_basename = file_name.to_s.split('.').first || "Example File"
file_ext = file_name.to_s.split('.').last || "csv"
### Must seperate basename and extension to array for tempfile new syntax
### https://ruby-doc.org/stdlib-3.0.2/libdoc/tempfile/rdoc/Tempfile.html#method-c-new
tmp_file = Tempfile.new([file_basename, ".#{file_ext}"], binmode: true)
tmp_file << str_data
return tmp_file
end
def sample_pdf_upload
sample_path = Rails.root.join("spec/fixtures/sample_file.pdf")
#fixture_file_upload(sample_path, 'application/pdf') ### MINITEST
Rack::Test::UploadedFile.new(sample_path) ### RSPEC
end
def sample_csv_upload
sample_path = Rails.root.join("spec/fixtures/sample_file.csv")
#fixture_file_upload(sample_path, 'text/csv') ### MINITEST
Rack::Test::UploadedFile.new(sample_path) ### RSPEC
end
def csv_upload(file)
sample_path = Rails.root.join("spec/fixtures/", file)
#fixture_file_upload(sample_path, 'text/csv') ### MINITEST
Rack::Test::UploadedFile.new(sample_path) ### RSPEC
end
def file_upload_from_string(str_file_data)
tmp_file = create_tempfile(str_file_data)
Rack::Test::UploadedFile.new(tmp_file)
end
def csv_string_from_data(headers:, row_data:)
csv_str = CSV.generate do |csv|
if headers.first.is_a?(Array)
headers.each do |header_row|
csv << header_row
end
else
csv << headers
end
row_data.each do |row|
csv << row
end
end
return csv_str
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment