2

I have a code that implements csv upload from services.

 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`

How do i write test for this?

Erica
  • 213
  • 2
  • 16

1 Answers1

3

I would start by placing fixture file(s) in ./spec/fixtures/*.csv (possibly in a subfolder, if needed). For example, something like:

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

In your spec, you then need to initialise some Project(s) and Week(s); then call the method with this fixture file. Something along the lines of:

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

This is, of course, only a guideline. For example, I've assumed you are using factory_girl, but this is not a requirement.

Hopefully this points you in the right direction - you will also benefit from adding a few more tests to cover edge cases. (What if the date is in the future? Or the distant past? Or the date is invalid? Or the billing hours is negative/blank/not a number? What if the csv file contains wrong headers? What if the file is huge, and is causing performance issues? Add tests for whatever your application needs to consider.)

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • Love some fixtures in tests. In class, instructors didn't think anyone could get test suite to run in under 30sec. Mine went in 2sec bc of fixtures. Also `factory_girl` is helpful too – Int'l Man Of Coding Mystery Oct 20 '17 at 16:49