Mario Uher
Mario Uher

Reputation: 12397

Capybara field.has_css? matcher

I'm using following spec with MiniTest::Spec and Capybara:

find_field('Email').must_have_css('[autofocus]')

to check if the field called 'Email' has the autofocus attribute. The doc says following:

has_css?(path, options = {})

Checks if a given CSS selector is on the page or current node.

As far as I understand, field 'Email' is a node, so calling must_have_css should definitely work! What I'm doing wrong?

Upvotes: 5

Views: 5162

Answers (3)

Mario Uher
Mario Uher

Reputation: 12397

Got an answer by Jonas Nicklas:

No, it shouldn't work. has_css? will check if any of the descendants of the element match the given CSS. It will not check the element itself. Since the autofocus property is likely on the email field itself, has_css? will always return false in this case.

You might try:

find_field('Email')[:autofocus].should be_present

this can also be done with XPath, but I can't recall the syntax off the top of my head.


My solution:

find_field('Email')[:autofocus].must_equal('autofocus')

Upvotes: 8

Derek Ekins
Derek Ekins

Reputation: 11391

I've not used MiniTest before but your syntax for checking for the attribute looks correct.

My concern would be with your use of find_field. The docs say:

Find a form field on the page. The field can be found by its name, id or label text.

It looks like you are trying to find the field based on the label. If so I would check that you have the for attribute on it and and that it has the correct id of the form field you are looking for. To rule out this being the issue you could temporarily slap an id your form field and look for that explicitly.

Upvotes: 0

Simon Bagreev
Simon Bagreev

Reputation: 2859

Off top of my head. Can you use has_selector?(). Using Rspec wit Capy:

page.should have_selector('email', autofocus: true)

Also check Capybara matchers http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers

Upvotes: 1

Related Questions