Read more

Test that a select field contains an option with Cucumber

Henning Koch
February 14, 2011Software engineer at makandra GmbH

This note describes a Cucumber step definition that lets you say:

Then "Mow lawn" should be an option for "Activity"
But "Reply support mail" should not be an option for "Activity"
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Note that this step checks whether an option is available, not that it is selected. There is a separate step to test that an option is selected.

Capybara (0.4.1 or higher)

Then /^"([^"]*)" should( not)? be an option for "([^"]*)"(?: within "([^\"]*)")?$/ do |value, negate, field, selector|
  with_scope(selector) do
    expectation = negate ? :should_not : :should
    field_labeled(field).first(:xpath, ".//option[text() = '#{value}']").send(expectation, be_present)
  end
end

Webrat

Then /^"([^"]*)" should( not)? be an option for "([^"]*)"$/ do |value, negate, field|
  expectation = negate ? :should_not : :should
  field_labeled(field).element.search(".//option[text() = '#{value}']").send(expectation, be_present)
end
Posted by Henning Koch to makandra dev (2011-02-14 14:53)