Darkisa
Darkisa

Reputation: 2037

Ruby, Cucumber, & Capybara: selecting using regex

I am trying to select an input node using Capybara:

When /^the shopper clicks the "(.+)" button$/ do |button|
    first(:css, text: /^#{button}/).click
end

The scenario that triggers the above step is:

And the shopper clicks the "PAY" button

The button in the view will always start with the text 'PAY' but it is followed by a space and then the total price of the products e.g. 'PAY $150'

The dollar amount will change but the PAY part won't. If I try the above code I get the following error:

And the shopper clicks the "PAY" button                   # features/step_definitions/shared_steps.rb:33
      unexpected '$' after '' (Nokogiri::CSS::SyntaxError)

How can I properly grab the PAY button using Capybara and Regex?

Upvotes: 0

Views: 355

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49890

The problem you're having is that you have specified a css selector type but not actually specified a CSS selector. Since it's an <input> element you could do

find(:css, 'input', text: /^#{button}/).click

However, since it's an input being used as a button I'm assuming it's of type submit, reset, image, or button. This means you can use the :button selector type (rather than :css) to make your clearer as to what you're actually doing. When finding a button Capybaras default behavior is to match on substrings so you should just be able to do

click_button(button)

which is the same as either of

find(:button, button).click
find_button(button).click

If that doesn't work for you please add the relevant HTML to your question.

As an aside, you should stay away from first whenever possible - it has a number of downsides.

Upvotes: 2

Related Questions