Cucumber: find the input with label text X?

Nathan Long picture Nathan Long · Nov 11, 2010 · Viewed 8.4k times · Source

In Cucumber, I'm trying to create a step like this:

Then I should see "Example business name" in the "Business name" input

I'd like the "Business name" input to be defined as "the input whose label has text "Business name."

Here's what I've got on the step so far:

Then /^I should see "([^"]*)" in the "([^"]*)" input$/ do |content, labeltext|
  # Not sure what to put here
end

In jQuery, I'd look for the label with that text, look at its "for" attribute, and find the input with that id. But the only selectors I've seen so far in Cucumber are these:

within("input:nth-child(#{pos.to_i}")

and

page.should have_content('foo')

Can anybody suggest a solution using the Webrat / Capybara selector syntax?

Answer

Nathan Long picture Nathan Long · Nov 11, 2010

Figured it out

You can find an input by its label text using find_field(labeltext).

# Example:
# 'I should see "Howdy" in the "Greeting" input' ("Greeting" is the label text)
Then /^I should see "([^"]*)" in the "([^"]*)" input$/ do |content, labeltext|
    find_field("#{labeltext}").value.should == content
end