follow me icons

Thursday, May 24, 2012

Capybara using contains to select an element

Suppose you have a select element that has a random number as the id like the one below:
< select class="select_xpath_class" name="myMethods[select_method_id_23749837]" id="select_method_id_23749837">
Please select... Select1 Select2 Select3

Capybara method of select won't work:"Select1", :from => "select_method_id")
This is because it will only find the exact match of the id.

To solve this we can use the find method directly with xpath:
find(:xpath, "//*[contains(@id, 'select_method_id')]").select("Select1")

1 comment:

  1. I couldn't get this solution to work but this is how I solved it (this was one of the first hits on google so I thought I'd help some other poor soul)"Select1", :from => find('select[id^="select_method_id"]')[:id])

    I'm just getting started with cucumber so original solution might be better if you can get it working otherwise try this.