我有以下代码:
element :header_upgrade_subscription, :xpath, "//a[text()='Upgrade subscription']"
element :header_change_subscription, :xpath, "//a[text()='Change subscription']"
if header_upgrade_subscription.visible?
change_subscription = header_upgrade_subscription
else
change_subscription = header_change_subscription
end
问题是如果header_upgrade_subscription不存在,它只会失败:
Capybara::ElementNotFound Exception: Unable to find xpath "//a[text()='Upgrade subscription']"
我知道在Capybara,你可以这样做:
(rdb:1) first(:xpath, "//a[text()='Upgrade subscription']")
nil
如果不存在则返回nil。我如何对SitePrism元素使用“first”方法?这就是我得到的:
(rdb:1) first(header_upgrade_subscription)
Capybara::ElementNotFound Exception: Unable to find xpath "//a[text()='Upgrade subscription']"
我喜欢使用“第一”方法,因为如果元素不存在,它没有等待时间。
感谢您的帮助!
答案 0 :(得分:4)
if has_header_upgrade_subscription? && header_upgrade_subscription.visible?
答案 1 :(得分:0)
这种方法最适合我,因为它灵活且一致。
假设你有页面类:
class SomePage < SitePrism::Page
element :some_message_banner, :css, "[data-component-property='message']"
# Within this class you can use it like this
def some_method
...
has_some_message_banner?(visible: false, text: "some text")
# or
has_some_message_banner?(visible: true)
end
end
在测试课程之外,您可以像这样使用它:
@some_page = SomePage.new
expect(@some_page.has_some_message_banner?(visible: true, text: "some text")).to be_truthy
# or this combination
@some_page.has_some_message_banner?(visible: false, text: "some text")
将返回true
或false
,具体取决于您要断言的内容