2014-02-25 81 views
1

随着我能抢的HTML特定的脚本标签如何使用页面对象宝石和红宝石

scripts = @browser.scripts 
index = scripts.find_index {|s| s.html.include? 'mytest.string'} 
icode = scripts[index].html 
etc. 

我要找的字符串是独一无二的,部分较长的Watir与脚本标签工作串。我需要验证更长的字符串是否正确。现在我按照上面的描述来做,但是如果可能的话,宁愿做页面对象的方式。我正在使用页面对象gem和ruby代码的其余部分。如果可能的话,希望对此脚本标记也做同样的处理。如果没有,我会坚持watir的方式。

一如既往的赞赏您的帮助。

回答

0

我假设你的HTML有这样的:

<html> 
    <body> 
    <script>other random script</script> 
    <script>some stuff mytest.string some other stuff</script> 
    <script>another random script</script> 
    </body> 
</html> 

要获得页面对象宝石脚本元素,你可以使用通用的element访问。然后,您可以将页面对象定义为:

class MyPage 
    include PageObject 

    element(:test_script, :script, :xpath => '//script[contains(text(), "mytest.string")]') 
end 

在此,我使用了:xpath定位器通过其文本查找脚本。使用:xpath通常不是建议的选择,但是我找不到另一种解决方案。你不能使用:text locator,因为Watir只返回可见的文本,这对脚本元素来说是没有用的。 :xpath定位器允许你绕过这个约束。

利用所定义的这个页面,你可以得到脚本元素的HTML如下:

page = MyPage.new(browser) 
page.test_script_element.html 
#=> "<script>some stuff mytest.string some other stuff</script>" 
+0

感谢贾斯汀。我会试试这个。希望避免xpath,但如果它是唯一的方法,那么我会使用它。 –