Ruby TypeError:没有将字符串隐式转换为数组 [英] Ruby TypeError: no implicit conversion of String into Array
问题描述
我有一个测试返回 TypeError: noimplicit conversion of String into Array
,当它遇到我的代码的某个部分时.如果我在 rspec 之外运行代码,它运行得很好,所以我不确定为什么会这样.
I have a test that returns TypeError: no impliciit conversion of String into Array
, when it hits a certain section of my code. If I run the code outside of rspec it runs just fine, so I'm not sure why this is happening.
require 'spec_helper'
require 'digital_ocean_size_list'
describe Chef::Knife::DigitalOceanSizeList do
subject { Chef::Knife::DigitalOceanSizeList.new }
let(:access_token) { 'FAKE_ACCESS_TOKEN' }
before :each do
Chef::Knife::DigitalOceanSizeList.load_deps
Chef::Config['knife']['digital_ocean_access_token'] = access_token
allow(subject).to receive(:puts)
end
describe "#run" do
it "should validate the Digital Ocean config keys exist" do
expect(subject).to receive(:validate!)
subject.run
end
....
正在测试以下代码
require 'chef/knife/digital_ocean_base'
class Chef
class Knife
class DigitalOceanSizeList < Knife
include Knife::DigitalOceanBase
banner 'knife digital_ocean size list (options)'
def run
$stdout.sync = true
validate!
size_list = [
ui.color('Slug', :bold)
]
client.sizes.all.each do |size|
size_list << size.slug.to_s
end
puts ui.list(size_list, :uneven_columns_across, 1)
end
end
end
end
类型错误来自 client.sizes.all.each.代码运行良好,我只收到来自 rspec 的类型错误.
The type error is coming from client.sizes.all.each. The code runs fine, I only get the type error when it's from rspec.
推荐答案
更改
size_list << size.slug.to_s
到
size_list << [size.slug.to_s]
在我的例子中,发生错误是因为我放入数组的值没有 []
,所以我用 []
包装它并且它可以工作.
In my case, the error occurred because the value I had put to array doesn't have []
, so I wrap it with []
and it works.
这篇关于Ruby TypeError:没有将字符串隐式转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!