Ruby - 没有将Array隐式转换为String

问题描述 投票:0回答:1

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

 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

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

当我包含一些看跌期权时,我得到一些非常不稳定的回应。该方法本身返回预期的结果。

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

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>
ruby watir
1个回答
2
投票

你的sic_code方法返回子表数组,这就是你有这个错误的原因。方法放置的东西并不重要,ruby中的每个方法都隐式返回其最后一行的结果,在你的情况下它是subtables.each do ... end,所以你有一个数组。

您需要显式返回所需的值。不确定我是否正确理解你在代码中做了什么,但尝试这样的事情:

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
© www.soinside.com 2019 - 2024. All rights reserved.