Capybara: is there opportunity to pass Capybara::Node::Element to jquery?

302 views Asked by At

I try to write code that can be used generally while page has a lot of elements with the same selectors and values. Sometimes I need to do things with a particular element that Capybara does not know - add or remove class, change background color.

When I need to select a particular element from many I get an array of Capybara::Node::Element after searching with the help of .all, for example. Is there an opportunity to pass one of such elements to jQuery in understandable format for jQ?

Simple passing it the same way as I pass css selectors gives an error

unknown error: Syntax error, unrecognized expression: #<Capybara::Node::Element:0x00000003e60d90>

Alternatives known for me are

  • :nth-of-type() /which I tried, and it did not work stable for me, still cannot fully understand why it worked only in majority of cases/

  • straight in jQuery: collecting all similar selectors to an array, slicing through it and making all the stuff I need. Acceptable, but has a disadvantage: provides more scripts in Capybara.

Is there chance to straightly pass a result of search with the help of .all to jQuery or any other alternatives?

P.S. Resuming briefly, the issue is to get one result that can be understandable by both Capybara and jQuery. Now when I am looping through similar elements I have a global counter with a number of the necessary one. But I have to provide different code basing on whether it would be used by Capybara (here it can be Capybara::Node::Element) or by jscripts (here I have to add slicing to the initial selector).

1

There are 1 answers

0
Thomas Walpole On BEST ANSWER

There is no way in Capybara itself to pass elements back to the browser for executing script (due to compatibility across drivers), however some of the drivers do support it. If using the selenium driver in capybara, passed elements are available in the arguments 'array', you can do something like this

el = page.find(:css, '#my_id') page.driver.browser.execute_script("$(arguments[0]).addClass('something');", el.native)