【问题标题】:NoMethodError: undefined method `errors' for []:ArrayNoMethodError:[]:Array 的未定义方法“错误”
【发布时间】:2018-10-18 08:25:17
【问题描述】:

当我为下面的代码运行 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

代码中url中的csv格式: 一旦我运行 Rake 任务,这将保存到数据库中

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

我做了什么调试:

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

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

那么,我该如何解决这个错误,我不知道做错了什么??

【问题讨论】:

  • 你有什么问题?
  • @sawa 这个问题从帖子中很清楚。
  • 人们总是无缘无故地标记问题,这太荒谬了。

标签: ruby-on-rails ruby rake rake-task rakefile


【解决方案1】:

如果您的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?

这就是你得到错误的原因。

【讨论】:

  • 非常感谢@MarekLipka
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
相关资源
最近更新 更多