Last Updated: February 25, 2016
·
1.5K
· dinks

Scoping in evaluate_script for Capybara

When you want to execute javascript in the browser session for Capybara, you would use

page.driver.evaluate_script

The main thing you might to know executing this is that the execution works on a strict mode and that means the eval is scoped within itself. It DOES NOT allow the declaration of variables or functions.

Eg. this doesn't work

var t = 10;
var p = function(){
  while(t > 0) {
    t--;
    doSomething();
  }
};

You will have to rewrite the function like this to work

(function(){
  var t = 10;
  var p = function(){
    while(t > 0) {
      t--;
      doSomething();
     }
  };
})()

and execute it like this

page.driver.evaluate_script "(function(){var t = 10;var p = function(){while(t > 0) {t--;doSomething();}};})()"