30

I have a really simple line in a test that calls execute script like this:

puts page.execute_script("return somefunction();").to_i.inspect

And in javascript I have a function like this:

function somefunction(){
    console.log("test");
    return 999;
}

The 'test' from the console log is getting logged out so it is running however...

Looking at the logs when running the test, the execute_script returns 0 not 999, so in rspec I can't get at the return value from the function, how do I make page.execute_script return that value from that function?

Rimian
  • 36,864
  • 16
  • 117
  • 117
CafeHey
  • 5,699
  • 19
  • 82
  • 145

1 Answers1

45

The Poltergeist driver is designed to return nil for execute_script:

def execute_script(script)
  browser.execute(script)
  nil
end

Poltergeist will only return a value if you use the evaluate_script:

def evaluate_script(script)
  browser.evaluate(script)
end

Capybara has corresponding methods for each - ie Session#execute_script and Session#evaluate_script. Your code should work if you switch to using evaluate_script (and as @AndreyBotalov points out, you also need to remove the return):

puts page.evaluate_script("somefunction();").to_i.inspect
Justin Ko
  • 46,526
  • 5
  • 91
  • 101
  • 1
    Note that this answer won't work with Selenium as Capybara would insert `return` itself. – Andrei Botalov Jul 27 '14 at 13:03
  • @AndreyBotalov, I corrected the code to remove the `return` when using `evaluate_script`. Including the `return` will throw an exception for both Selenium and Poltergeist. – Justin Ko Jul 27 '14 at 20:00