Ruby TypeError: no implicit conversion of String into Array

*爱你&永不变心* 提交于 2020-01-04 09:19:12

问题


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
....

It's testing the following code

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

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.


回答1:


Change

size_list << size.slug.to_s

To

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.



来源:https://stackoverflow.com/questions/26820612/ruby-typeerror-no-implicit-conversion-of-string-into-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!