ruby-on-railsrubyrakerake-taskrakefile

NoMethodError: undefined method `errors' for []:Array


I get NoMethodError when I run test for the code below

csv_importer.rb

require 'csv_importer/engine'

class WebImport
  def initialize(url)
    @url = url
  end

  def call
    url = 'http://example.com/people.csv'
    csv_string = open(url).read.force_encoding('UTF-8')

    string_to_users(csv_string)
  end

  def string_to_users(csv_string)
    counter = 0
    duplicate_counter = 0

    user = []
    CSV.parse(csv_string, headers: true, header_converters: :symbol) do |row|
      next unless row[:name].present? && row[:email_address].present?
      user = CsvImporter::User.create row.to_h
      if user.persisted?
        counter += 1
      else
        duplicate_counter += 1
      end
    end
    p "Email duplicate record: #{user.email_address} - #{user.errors.full_messages.join(',')}" if user.errors.any?

    p "Imported #{counter} users, #{duplicate_counter} duplicate rows ain't added in total"
  end
end

csv_importer_test.rb

require 'csv_importer/engine'
require 'test_helper'
require 'rake'

class CsvImporterTest < ActiveSupport::TestCase

  test 'truth' do
    assert_kind_of Module, CsvImporter
  end

  test 'should override_application and import data' do
    a = WebImport.new(url: 'http://example.com/people.csv')
    a.string_to_users('Olaoluwa Afolabi')# <-- I still get error even I put a comma separated list of attributes that is imported into the db here.
    assert_equal User.count, 7
  end
end

csv format in the url in the code: This saves into DB once I run the Rake Task

Name,Email Address,Telephone Number,Website
Coy Kunde,stone@stone.com,0800 382630,mills.net

What I have done to debug:

I use byebug and I figured out the in csv_importer_test.rb, the line where I have a.string_to_users('Olaoluwa Afolabi') is throwing error. See byebug error below:

byebug error

So, I when I run rails test, I get the error below:

test error

So, how do I solve this error, I have no clue what am doing wrong??


Solution

  • If you don't have any row in your csv_string, this line:

    user = CsvImporter::User.create row.to_h
    

    isn't executed, so user variable holds previous value, which is []:

    user = []
    

    As we know, there's no method errors defined for Array, yet you try to call it in this line:

    p "Email duplicate record: #{user.email_address} - #{user.errors.full_messages.join(',')}" if user.errors.any?
    

    and that's why you get an error.