p.matsinopoulos
p.matsinopoulos

Reputation: 7810

What is the correct way to get selected option text using site_prism?

I have a site_prism element that points to a select box. Like this:

class MyPageObject < SitePrism::Page
  element :my_select_box, '#select-box-id'
end

Although I have a way to get the selected option value, with this:

my_page_object.my_select_box.value

I cannot find a nice way to get the selected option text. The only workaround that I have found is this:

my_page_object.my_select_box.find("option[selected]").text

Is there a better way to do that with SitePrism API? Because the above workaround uses a mix of SitePrism and capybara API, which does not seem to be ideal to me.

Upvotes: 2

Views: 1744

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49910

I've never done this, but one way would probably be to define :my_select_box as a section and then have the selected element accessed under that

class SelectSection < SitePrism::Section
  element :selected, 'option[selected]'
end

class MyPageObject < SitePrism::Page
  section :my_select_box, SelectSection, '#select-box-id'
end

which should let you access

my_page_object.my_select_box.selected.text

A good question however is why you want to access the text - If it's because you want to verify the text of the selected item against a known text, you're better off actually declaring the element as a select using Capybaras selectors so that you can can use the builtin finder options

class MyPageObject < SitePrism::Page
  element :my_select_box, :select, 'select-box-id' # since it's now using Capybaras :select selector it's no longer a css selector so no # in front
end

which then should let you do

expect(my_page_object).to have_my_select_box(selected: 'the text expected to be selected')

Upvotes: 4

Related Questions