当我为下面的代码运行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格式: 一旦我运行Rake任务
,这将保存到DB中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')
所在的行rails test
正在抛出错误。请参阅下面的byebug错误:
所以,当我运行web3.eth.getBalance(address)
时,我收到以下错误:
那么,我如何解决这个错误,我不知道到底做错了什么?
答案 0 :(得分:3)
如果您的csv_string
中没有任何行,则此行:
user = CsvImporter::User.create row.to_h
未执行,因此user
变量包含以前的值,即[]
:
user = []
我们知道,errors
没有定义Array
方法,但您尝试在此行中调用它:
p "Email duplicate record: #{user.email_address} - #{user.errors.full_messages.join(',')}" if user.errors.any?
这就是你收到错误的原因。