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

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

当我 运行 test 下面的代码

时,我得到 NoMethodError

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格式在url代码中: 一旦我 运行 Rake Task

这将保存到数据库中
Name,Email Address,Telephone Number,Website
Coy Kunde,stone@stone.com,0800 382630,mills.net

我调试的内容:

我使用 byebug 并且发现 csv_importer_test.rba.string_to_users('Olaoluwa Afolabi') 所在的行抛出错误。请参阅下面的 byebug 错误:

所以,当我 运行 rails test 时,我得到以下错误:

所以,我该如何解决这个错误,我不知道哪里做错了??

如果您的 csv_string 中没有任何行,则此行:

user = CsvImporter::User.create row.to_h

没有被执行,所以 user 变量保持之前的值,即 []:

user = []

我们知道,没有为 Array 定义方法 errors,但您尝试在这一行中调用它:

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

这就是您收到错误的原因。