Object.respond_to?从数组

时间:2016-05-13 10:30:45

标签: ruby unit-testing reflection testunit

我实现页面对象,并编写测试来验证它们。我希望通过将元素名称存储在符号数组中并循环遍历它来简化测试,但它失败了。

def setup
  @browser = Watir::Browser.new :phantomjs
  @export_page = ExportPage.new @browser
  @assets = %i{:section :brand}
end

-

#PASSES

def test_static
    $stdout.puts :section.object_id
    raise PageElementSelectorNotFoundException, :section unless @export_page.respond_to? :section
end

> # 2123548

这是因为目标类确实实现了这个方法,但是:

#FAILS

def test_iterator
  @assets.each do |selector|
    $stdout.puts selector.class
    $stdout.puts selector.object_id
    $stdout.puts :section.object_id
    raise PageElementSelectorNotFoundException, selector unless @export_page.respond_to? selector
  end
end


> # Testing started at 11:19 ...
> # Symbol
> # 2387188
> # 2123548

PageElementSelectorNotFoundException: :section missing from page
~/src/stories/test/pages/export_page_test.rb:20:in `block in test_iterator'

正如您所看到的,我已经检查了符号的对象ID,它们看起来确实有所不同。这可能是它失败的原因吗?有解决方案吗?

2 个答案:

答案 0 :(得分:1)

当使用短符号来声明原子数组时,不应该在那里放置冒号:

- %i{:section :brand}   # incorrect
+ %i{section brand}     # correct

@assets = %i{:section :brand}实际定义的是以下数组:

[:':section', :':brand']

答案 1 :(得分:0)

请勿使用%i {}表示法,因为它会自动生成您指定的文字的符号。

这转换为:

@assets = [:":section", :":brand"]

技术上是一个符号数组,而不是你想要的符号。这就是对象ID在您的测试中不匹配的原因。

在Ruby 2.0中添加了%i {}语法。在可能支持旧版Ruby的代码中使用时,请使用传统的符号数组:

@assets = [:section, :brand]