Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get select value of dropdown for capybara testing

I have to write tests for a web site. I am trying to get the selected value of a dropdown box. So far i can get the contents of the dropdown by doing

find_field('restrictions__rating_movies').text 

returns - Don't Allow Movies G PG M R13 R15 R16 R18 R RP16 Allow All Movies

I can get the value of the selected object.

find_field('restrictions__rating_movies').value 

returns - 1000

This does not help me much though because i am trying to get the text of the selected item from a drop down box.

<select class="" id="restrictions__rating_movies" name="restrictions[][rating_movies]">             <option value="0">Don't Allow Movies</option> <option value="100">G</option> <option value="200">PG</option> <option value="300">M</option> <option value="325">R13</option> <option value="350">R15</option> <option value="375">R16</option> <option value="400">R18</option> <option value="500">R</option> <option value="600">RP16</option> <option value="1000" selected="selected">Allow All Movies</option></select> 

in this case shown i need to get the value 'Allow All Movies' I have tried many different combinations of the above two examples.

like image 337
Brandon Avatar asked Jul 16 '12 05:07

Brandon


People also ask

How do you select options in capybara?

Method: Capybara::Node::Actions#select If the select box is a multiple select, #select can be called multiple times to select more than one option. The select box can be found via its name, id, test_id attribute, or label text. The option can be found by its text.

How do I check a checkbox in capybara?

on Chrome (and surely other browsers), you can "inspect element" and then by right clicking on the element you are interested in, there is 'copy xpath' if you don't know what xpath was, now you do. Show activity on this post. You can also check that all the checkboxes are not checked with this example.

What is RSpec capybara?

Capybara helps you test web applications by simulating how a real user would interact with your app. It is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in.


2 Answers

There's a have_select matcher if you use Capybara with Rspec:

expect(page).to have_select(   'my-select',         # locator   selected: 'Option 2' # option )  
Parameters:

Locator (String) (defaults to: nil) — The label, name or id of a select box Options (Hash) using :selected (String, Array) — Options which should be selected

like image 94
gylaz Avatar answered Sep 16 '22 13:09

gylaz


find_field('restrictions__rating_movies').find('option[selected]').text 
like image 28
Brandon Avatar answered Sep 17 '22 13:09

Brandon