在水豚中使用execute_script时如何返回值? [英] How to return a value when using execute_script in capybara?
问题描述
在测试中,我有一条非常简单的代码行,调用执行脚本,如下所示:
I have a really simple line in a test that calls execute script like this:
puts page.execute_script("return somefunction();").to_i.inspect
在javascript中,我有一个像这样的函数: / p>
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...
运行测试时查看日志,execute_script返回0而不是999,所以在rspec中我无法从函数获得返回值,如何使page.execute_script从该函数返回该值?
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?
推荐答案
Poltergeist驱动程序旨在为< a href = http://rubydoc.info/gems/poltergeist/Capybara/Poltergeist/Driver#execute_script-instance_method> execute_script
:
The Poltergeist driver is designed to return nil for execute_script
:
def execute_script(script)
browser.execute(script)
nil
end
如果您使用 evaluate_script
:
Poltergeist will only return a value if you use the evaluate_script
:
def evaluate_script(script)
browser.evaluate(script)
end
Capybara每种都有相应的方法-即 Session#execute_script
和 Session#evaluate_script
。如果您切换到使用 evaluate_script
,则您的代码应该可以正常工作(正如@AndreyBotalov指出的那样,您还需要删除 return
):
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
这篇关于在水豚中使用execute_script时如何返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!