I’ve been using Cucumber and Webrat for only a couple months now. Today I needed something new and it wasn’t obvious how to make it work.
Here’s an example of a test in Cucumber:
Given I am Sam When I follow "Foo" Then the "Bar" field should contain "Baz"
Which relies on Webrat:
Then /^the "([^"]*)" field should contain "([^"]*)"$/ do |field, value|
field_labeled(field).value.should =~ /#{value}/
end
But what if it’s not a text field? What if it’s a select? Then we need to check which value is selected.
Given Sam I am When I follow "Foo" Then "Baz" should be selected for "Bar"
Here’s my solution:
Then /^"([^"]*)" should be selected for "([^"]*)"$/ do |value, field|
field_labeled(field).element.search(".//option[@selected = 'selected']").inner_html.should =~ /#{value}/
end
Hope this helps!






Perfect timing. Exactly what I was looking for this morning. Thanks!
Legend, exactly what I need!
This came in very handy, thanks
Thanks for this solution, saved me some time!
Perfect, thank you for your post
I don’t know if this is a new feature, but i’m using webrat 0.6 and
field_labeled(field).value
works just fine for select boxes also. You’re then just matching against the option value, not the text.
Exactly what I needed, but did you forget to escape auotes in your regexp ?
“([^"]*)” instead of “([^"]*)”
It works for me as is. Those quotes aren’t delimiters in this context, and I want to capture everything between the quotes in the () backreference.
Very Well then.
It didn’t work for me because of the field_labeled.
It works now with field_named(field) :)
Thanks for your post !
Great post, worked like a charm.
Florent, your fix worked for me as well. field_labeled was always giving an error saying it couldn’t find the field. Thanks!
Thanks for the tip! I’m actually using Capybara so I had to rework your step to get it to work. For those other Capybara users out there… this is what you need:
Then /^”([^"]*)” should be selected for “([^"]*)”$/ do |value, field|
find_field(field).node.xpath(“.//option[@selected = 'selected']“).inner_html.should =~ /#{value}/
end
Cheers,
Ganesh
Thanks for the tip. I suggest that you use the following regex to insure that you don’t get false positives:
/^#{value}$/
e.g. Without the anchors, if the selected value is “Mrs” and I expect “Mr”, it will still match and return a false positive result.
Ganesh, I tried using your Capybara snippet of this and get the following error:
undefined method ‘xpath’ for # (NoMethodError)
Which version of Capybara are you using? I am using 0.4.0 with selenium-webdriver version 0.1.0.
BTW, I got it to work with Capybara (0.4.0) with WebDriver (0.1.0) like this:
find_field(field).native.value =~ /^#{value}$/
It seems it is more complicated to do it outside of a browser test…
huge time saver. thanks.