Тестирование лямбды

Я создаю функцию импорта, которая импортирует CSV-файлы в несколько таблиц. Я сделал модуль под названием CsvParser, который анализирует файл CSV и создает записи. Мои модели, которые получают действия создания, расширяют CsvParser. Они вызывают CsvParser.createи передают правильный порядок атрибутов и необязательную лямбду с именем value_parser. Эта лямбда преобразует значения в хэше в предпочтительный формат.

class Mutation < ActiveRecord::Base
  extend CsvParser

  def self.import_csv(csv_file)
    attribute_order = %w[reg_nr receipt_date reference_number book_date is_credit sum balance description]

    value_parser = lambda do |h|
      h["is_credit"] = ((h["is_credit"] == 'B') if h["is_credit"].present?)
      h["sum"] = -1 * h["sum"].to_f unless h["is_credit"]
      return [h]
    end

    CsvParser.create(csv_file, self, attribute_order, value_parser)    
  end
end

Причина, по которой я использую лямбда вместо проверок внутри метода CsvParser.create, заключается в том, что лямбда похожа на бизнес-правило, принадлежащее этой модели.

Мой вопрос в том, как мне проверить эту лямбду. Должен ли я проверить это в модели или CsvParser? Должен ли я тестировать саму лямбду или результат массива метода self.import? Может быть, я должен сделать другую структуру кода?

Мой CsvParser выглядит следующим образом:

require "csv"

module CsvParser

  def self.create(csv_file, klass, attribute_order, value_parser = nil)
    parsed_csv = CSV.parse(csv_file, col_sep: "|")

    records = []    

    ActiveRecord::Base.transaction do
      parsed_csv.each do |row|
        record = Hash.new {|h, k| h[k] = []}      
        row.each_with_index do |value, index|
          record[attribute_order[index]] = value
        end 
        if value_parser.blank?
          records << klass.create(record)
        else
          value_parser.call(record).each do |parsed_record|
            records << klass.create(parsed_record)
          end
        end
      end 
    end
    return records
  end

end

Я тестирую сам модуль:require 'spec_helper'

describe CsvParser do

  it "should create relations" do
    file = File.new(Rails.root.join('spec/fixtures/files/importrelaties.txt'))
    Relation.should_receive(:create).at_least(:once)
    Relation.import_csv(file).should be_kind_of Array 
  end

  it "should create mutations" do
    file = File.new(Rails.root.join('spec/fixtures/files/importmutaties.txt'))
    Mutation.should_receive(:create).at_least(:once)    
    Mutation.import_csv(file).should be_kind_of Array
  end

  it "should create strategies" do
    file = File.new(Rails.root.join('spec/fixtures/files/importplan.txt'))
    Strategy.should_receive(:create).at_least(:once)
    Strategy.import_csv(file).should be_kind_of Array
  end

  it "should create reservations" do
    file = File.new(Rails.root.join('spec/fixtures/files/importreservering.txt'))
    Reservation.should_receive(:create).at_least(:once)
    Reservation.import_csv(file).should be_kind_of Array
  end

end
5
задан Harm de Wit 11 April 2012 в 10:37
поделиться