NeyLive
NeyLive

Reputation: 417

Capybara find_field & has_selector not working

I am using Capybara and getting errors from the finders 'find_field' & 'has_selector'.

I have tried using them like this:

page = visit "http://www.my-url-here.com"   
next if page.has_selector?('#divOutStock')
page.find_field('#txtQty').set('9999')

has_selector returns the error: "NoMethodError: undefined method `has_selector?' for {"status"=>"success"}:Hash"

find_field cannot find the field. (It is present on the page and is not a hidden field.)

I have also tried using fill_in to set the field value, that doesn't work either.

How can I get this to work with Capybara?

Upvotes: 0

Views: 518

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49880

You have a couple of issues in your code

  1. page is just an alias for Capybara.current_session. If you assign to it you're creating a local variable and it's no longer a session

  2. find_field takes a locator - http://www.rubydoc.info/gems/capybara/Capybara/Node/Finders#find_field-instance_method - which will be matched against the id, name, or label text. It does not take a CSS selector

Your code should be

page.visit "http://www.my-url-here.com"   
next if page.has_selector?('#divOutStock')
page.find_field('txtQty').set('9999')

and you could rewrite the last line as

page.fill_in('txtQty', with: '9999')

Also you should note that (if using a JS capable driver) has_selector? will wait up to Capybara.default_max_wait_time for the #divOutStock to appear. If it's not usually going to be there and you want to speed things up a bit you could do something like

page.visit "http://www.my-url-here.com"   
page.assert_text('Something always on page once loaded') #ensure/wait until page is loaded
next if page.has_selector?('#divOutStock', wait: 0) # check for existence and don't retry
page.fill_in('txtQty', with: '9999')

Upvotes: 1

Related Questions