当我运行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,[email protected],0800 382630,mills.net
我为调试所做的工作:
我使用byebug
并找出了 in csv_importer_test.rb
,我所在的行a.string_to_users('Olaoluwa Afolabi')
抛出错误。请参阅下面的错误错误:
所以,当我运行时rails test
,我收到以下错误:
那么,我该如何解决这个错误,我不知道做错了什么??
如果您的 中没有任何行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?
这就是为什么你会得到一个错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句