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

1

6

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>
Stramonium answered 5/8, 2016 at 6:13 Comment(1)
Calling the function directly is not different from invoking the click. There must be something else that causes this problem. Also, I don't believe you that you haven't "found [a] source on the Internet which taught to do this.". This is a fairly common task, so you should improve your search skills and additionally start to read the API, because it's not very long.Champac
H
19

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

Hydrotropism answered 5/8, 2016 at 7:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.