Ruby-不会将Array隐式转换为String

时间:2018-11-07 16:43:39

标签: ruby watir

执行测试时出现错误。

 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>

1 个答案:

答案 0 :(得分: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