Ruby - 没有将数组隐式转换为字符串

Ruby - no implicit conversion of Array into String

我在执行测试时遇到错误。

 Failure/Error: expect(industry_sic_code).to include page.sic_code

 TypeError:
   no implicit conversion of Array into String
 # ./spec/os/bal/company/company_filter_clean_harbors_industries_stub.rb:62:in `block (2 levels) in <top (required)>'

方法:

def sic_code
  subtables = @b.table(:class => 'industry-codes').tables(:class => 'industry-code-table')
  subtables.each do |subtable|
    if subtable.tbody.h4.text == "US SIC 1987:"
      subtable.tr.next_siblings.each do |tr|
       codes = tr.cell
       puts codes.text.to_s
      end
    end
  end
end

测试:

  it 'Given I search for a random Clean Harbors Industry' do

  #Pick a random clean industry from the file
    data = CSV.foreach(file_path, headers: true).map{ |row| row.to_h }
    random = data.sample

    random_industry = random["Class"]
    industry_sic_code = random["SIC Code"]
  end

  it 'Then the result has the expected SIC code' do
    page = DetailPage.new(@b)
    page.view

    expect(industry_sic_code).to include page.sic_code
  end

我试图将每个变量隐式更改为字符串,但它仍然抱怨数组问题。

当我包含一些 puts 语句时,我得到了一些非常不稳定的响应。方法本身 returns 预期结果。

当我在测试中使用该方法时,我得到了下面的代码乱码。

here are the sic codes from the method
5511

Here are the codes from the test
#<Watir::Table:0x00007fa3cb23f020>
#<Watir::Table:0x00007fa3cb23ee40>
#<Watir::Table:0x00007fa3cb23ec88>
#<Watir::Table:0x00007fa3cb23ead0>
#<Watir::Table:0x00007fa3cb23e918>
#<Watir::Table:0x00007fa3cb23e738>
#<Watir::Table:0x00007fa3cb23e580>

您的 sic_code 方法 returns 子表数组,这就是您出现此错误的原因。该方法放一些东西并不重要,ruby 中的每个方法都隐含地 return 其最后一行的结果,在您的情况下它是 subtables.each do ... end,所以您有一个数组。

您需要明确 return 需要的值。不确定我是否正确理解了您在代码中所做的事情,但请尝试这样的操作:

def sic_code
  subtables = @b.table(:class => 'industry-codes').tables(:class => 'industry-code-table')
  result = [] # you need to collect result somewhere to return it later
  subtables.each do |subtable|
    if subtable.tbody.h4.text == "US SIC 1987:"
      subtable.tr.next_siblings.each do |tr|
        codes = tr.cell
        result << codes.text.to_s
      end
    end
  end
  result.join(', ') 
end