Verifying select field value with Cucumber and Webrat
May.31, 2009 in
programming
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!

June 16th, 2009 at 9:54 am
Perfect timing. Exactly what I was looking for this morning. Thanks!
September 4th, 2009 at 12:02 am
Legend, exactly what I need!
October 12th, 2009 at 7:08 am
This came in very handy, thanks
November 19th, 2009 at 3:06 pm
Thanks for this solution, saved me some time!
January 8th, 2010 at 12:58 pm
Perfect, thank you for your post
January 21st, 2010 at 11:52 pm
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.
February 25th, 2010 at 11:58 am
Exactly what I needed, but did you forget to escape auotes in your regexp ?
“([^\"]*)” instead of “([^"]*)”
February 25th, 2010 at 12:04 pm
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.
February 26th, 2010 at 7:48 am
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 !