Ponchooo
Ponchooo

Reputation: 83

Selecting the content within <option></option> tags

Writing tests using cucumber and SitePrism, I have the following HTML on the page...

<select name="product_status_id" id="product-status" class="pull-right">
   <option value="">Select a Status</option>
   <option value="1">Active Product</option>
   <option value="2">Inactive Product</option>
</select>

Currently, the element selector I have set for this dropdown is...

 element :status_active, '#product-status'

I first set the 1st value in my test to "Active Product"...

And(/^I select the status of Active$/) do
   @page.product.status_active.select("Active Product")
end

And then verify the value saved is the status of "Active Product"

And(/^the product values entered should match those which were saved$/) do
   @page.product.status_active.value.should == "1"
end 

However, if these values were to be switched around, with "Active Product" as value="2" and "Inactive Product" as value="1", the test would not longer be verifying that the field is set to the "Active Product" value.

Is there an instance that I can write that checks for the contents between the option tags?

<option>want to select content here</option> 

When I write the following...

@page.product.status_active.text.should == “Active Product”

The following is returned...

"Select a Status Active Product Inactive Product”

So the .text method doesn't seem to be an adequate solution here.

What can be written to select the content between the option tags?

Upvotes: 1

Views: 130

Answers (2)

Phil
Phil

Reputation: 916

If I understand you correctly, you want to be able to select something from a dropdown list only using the text between the option tags.

Once you find the css for your selector, you can use the text matcher to find the option you need. It also makes for some specs that can be easily read and maintained.

Here it is using capybara:

page.find('#product-status option', :text => 'Active Product').click

Upvotes: 0

Matt Metzger
Matt Metzger

Reputation: 601

When an option is selected, it should have a selected attribute like this: <option value="1" selected>Active Product</option> which you can use as a selector.

So you could find the selected option like this: @page.product.status_active.find('option[selected]')

So to verify the text of the selected option, you would do: @page.product.status_active.find('option[selected]').text.should == “Active Product”


On a related note, I have actually found myself doing this so frequently, I added the following to my test suite: class Capybara::Node::Element def selected_option self.find('option[selected]') end end

This adds a selected_option to capybara elements. With that, you could just do this @page.product.status_active.selected_option.text.should == “Active Product”

Upvotes: 1

Related Questions