Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function on a page with Capybara/Poltergeist?

I have a page with JS functions (which are called on mouse click) within <script> ... </script> tags. While I was testing I had encountered problems with .click method not working many times. Therefore I decided to simply call that function manually. However I found no source on the Internet which taught to do this.

I want to avoid clicking the links and simply call for doSumbit('5'). Thank you!

The JS functions are:

<script language="javascript">
function doSubmit(infoTypeId) {
    document.forms[1].INFOTYPEID.value = infoTypeId;
    document.forms[1].action = document.forms[1].action + "#" + infoTypeId;
    document.forms[1].submit();
    document.forms[0].INFOTYPEID.value = infoTypeId;
    document.forms[0].submit();
}
function doSubmitOne(infoTypeId) {
    document.forms[0].INFOTYPEID.value = infoTypeId;
    document.forms[0].submit();
}
</script>

and the on-click links are:

 <a href="javascript:doSubmit('11')" >Engine News<br></A>
<a href="javascript:doSubmit('5')" >Parts Identification<br></A>
like image 356
Riman Avatar asked Aug 05 '16 06:08

Riman


1 Answers

You can run arbitrary JS with execute_script

page.execute_script("doSubmit('5')")

if you expect a return value use evaluate_script - it's all documented here - http://www.rubydoc.info/gems/capybara/Capybara/Session#evaluate_script-instance_method

Of course if you're actually testing an app, you'd be much better off figuring out why click isn't working for you and fixing that, since by just calling JS functions you're not actually testing that your app works.

EDIT: typo doSubit changed to doSubmit

like image 64
Thomas Walpole Avatar answered Sep 19 '22 12:09

Thomas Walpole