2016-03-24 63 views
1

我使用page-object-gem并尝试查找当一组text_field具有无限次出现次数时定义页面元素的最佳方式。克隆行的页面元素定义

在页面加载的HTML类似于以下:

<div><input id="dx_1_code" value=""/> <input id="dx_1_dos" onblur="clone($(this),false)" value=""/></div>

如果用户切换到最后一个输入的则有新行克隆与用HTML递增ID值喜欢如下:

<div><input id="dx_2_code" value=""/> <input id="dx_2_dos" onblur="clone($(this),false)" value=""/></div> 
<div><input id="dx_3_code" value=""/> <input id="dx_3_dos" onblur="clone($(this),false)" value=""/></div> 

我的第一次尝试是定义我的类,如下所示:

class SamplePage 
    include PageObject 
    include DataMagic 

    text_field(:dx_1, :id => "dx_1_code") 
    text_field(:dx_2, :id => "dx_2_code") 
    text_field(:dos_1, :id => "dx_1_dos") 
    text_field(:dos_2, :id => "dx_2_dos") 

end 

但是,我很快结束了很多冗余条目。

有没有更好的方法来处理未知的数字或这样的项目在元素设置和使用populate_page_with方法?

回答

1

元素被编入索引,这使得它们成为索引属性功能的良好候选。 indexed_property可让您定义在访问元素时替换数字的定位器。页面对象将是这样的:

class MyPage 
    include PageObject 

    indexed_property(:dx, [ 
    [:text_field, :code, {id: 'dx_%s_code'}], 
    [:text_field, :dos, {id: 'dx_%s_dos'}], 
    ]) 
end 

前两行将然后用要输入:

page = MyPage.new(browser) 
page.dx[1].code = 'a' 
page.dx[1].dos = 'b' 
page.dx[2].code = 'c' 
page.dx[2].dos = 'd' 

不幸的是,为populate_page_with方法与索引属性工作没有内置的方式。和其他任何东西一样,你可以攻击一些东西。 populate_page_with方法寻找“元素”方法以及setter方法。通过将自己添加到页面对象中,可以使用该方法。

class MyPage 
    include PageObject 

    indexed_property(:dx, [ 
    [:text_field, :code, {id: 'dx_%s_code'}], 
    [:text_field, :dos, {id: 'dx_%s_dos'}], 
    ]) 

    # Method for inputting the various dx code/dos values based on a Hash 
    def dx=(values) 
    values.each_pair do |index, fields| 
     fields.each_pair do |field, value| 
     dx[index].send("#{field}=", value) 
     end 
    end 
    end 

    # This is so that populate_page_with can check that the element is enabled/visible 
    def dx_element 
    dx[1].code_element 
    end 
end 

这会给你发送一个散列密钥是索引和值是该索引的字段/值使用populate_page_with的能力。我们之前做过的页面的输入现在可以写成:

page = MyPage.new(browser) 
page.populate_page_with(dx: { 
    1 => {code: 'a', dos: 'b'}, 
    2 => {code: 'c', dos: 'd'} 
})