How to get placeholder value using assert_selector in rails

Viewed 212

How do I get the placeholder value from an input bar using assert_selector in rails ?

<input placeholder="hello world"  value="<%= params[:query] %>" required>

I want to check is placeholder has hello in it

2 Answers

While the answer by Lam Phan does answer the question, resorting to writing XPath queries when CSS has what you need isn't usually the best idea from a readability/understandability perspective.

CSS has a number of attribute selectors, the most useful for testing usually being

  • = matching
  • *= containing
  • ^= begins with
  • ~= whitespace separated matching

You can see the full set at https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

In this case that means you could do any of

assert_selector('input[placeholder*="hello"]') # contains 'hello'
assert_selector('input[placeholder~="hello"]') # contains the word 'hello'
assert_selector('input[placeholder^="hello"]') # starts with 'hello'

Another option would be take advantage of the fact that the Capybara :field selector has a placeholder filter - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector.rb#L34 - which takes a regex - so you could do

assert_field(placeholder: /hello/)

which is the same as

assert_selector(:field, placeholder: /hello/)

you could use xpath and verify that there's an input element whose's placeholder contains 'hello'

assert_selector(:xpath, './/input[contains(@placeholder,"hello")]')

if you want to check exactly an input with id

assert_selector(:xpath, './/input[@id="input_id"][contains(@placeholder,"hello")]')

im not sure there's a helper method that check regex something like ~= /.*hello.*/, if you want to do that, you still have another choice

placeholder = find('#input_id')['placeholder'] # or use :xpath
assert_match /.*hello.*/, placeholder
Related