Zack
Zack

Reputation: 2497

Getting selected value of a select 2 in Capybara

I have a select2 dropdown in my rails code that I am trying to set and assert via capybara.

<select class="select optional select2-offscreen" id="bar_effort" name="bar[effort]" tabindex="-1"><option value=""></option>
   <option value="0">Small</option>
   <option value="1">Medium</option>
   <option value="2">Large</option>
   <option value="3">Extra Large</option>
</select>

To set the value I have the following (which works fine):

 def effort=(effort)
    @page.select(effort, :from => 'bar_effort')
 end

Once the value has been set, I close the form and when I return back to the form, I want to assert the value I set is still selected. To do this I attempted the following:

  def effort 
    @page.find(:css, '#bar_effort').value #version 1
  end

  def effort
    @page.find(:css, '#bar_effort').text #version 2
  end

Version 1 gave me "0" when I was expecting "Small"
Version 2 gave me "Small Medium Large Extra Large" when I was expecting "Small"

Upvotes: 0

Views: 1089

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

For a select list, the value method will return the selected option's text only if it does not have a value attribute.

To get the selected option's text, you will need to manually locate the option and get its text:

@page.find('#bar_effort').all('option').find(&:selected?).text
#=> "Small"

Upvotes: 1

Related Questions