Can't seem to use SitePrism's element.visible? if the element doesn't exist

2.7k views Asked by At

I have the following codes:

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

The problem is if header_upgrade_subscription doesn't exist, it just fails with:

Capybara::ElementNotFound Exception: Unable to find xpath "//a[text()='Upgrade subscription']"

I know that in Capybara, you can do:

(rdb:1) first(:xpath, "//a[text()='Upgrade subscription']")
nil

and it would return nil if it doesn't exist. How would I use "first" method against the SitePrism element? This is what I get:

(rdb:1) first(header_upgrade_subscription)
Capybara::ElementNotFound Exception: Unable to find xpath "//a[text()='Upgrade subscription']"

I like using the "first" method as it has no wait time if the element doesn't exist.

Thanks for your help!

2

There are 2 answers

0
Matt Van Horn On BEST ANSWER
if has_header_upgrade_subscription? && header_upgrade_subscription.visible?
0
Aleks Tkachenko On

This approach works best for me as its flexible and consistent.

Say you have page class:

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

Outside of the class in tests you can use it like this:

@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")

will return true or false depending on what you want to assert