Posted about 1 month ago. Visible to the public. Repeats.

Capybara: you can use `evaluate_async_script` to execute asynchronous JavaScript

Capybara provides execute_script and evaluate_script to execute JavaScript code in a Selenium-controlled browser. This however is not a good solution for asynchronous JavaScript.

Enter evaluate_async_script, which allows you to execute some asynchronous code and wait until it finishes. There is a timeout of a couple of seconds, so it will not wait forever.

Use it like this:

Copy
page.evaluate_async_script(<<~JS) let [done] = arguments doSomethingAsynchronous().then(() => { done() // call this to indicate we're done }) JS

You can return results to Ruby by passing them to the done callback:

Copy
result = page.evaluate_async_script(<<~JS) let [done] = arguments doSomethingAsynchronous().then(() => { done("some result") }) JS

Finally, you can pass additional object from Ruby to Javascript:

Copy
result = page.evaluate_async_script(<<~JS, arg1, arg2) let [arg1, arg2, done] = arguments doSomethingAsynchronous().then(() => { done("some result") }) JS

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Tobias Kraze
Last edit:
about 1 month ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more