DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

Run Javascript by Capybara feature test

🔗 Parent Note

🤔 Situation

Let's say you have following iframe. And, you want to assert that a selector inside the iframe is not shown when the iframe height is too short.

<div>
  <iframe src='https://n350071.com' id='n350071-frame'></iframe>
</div>

👍 Solution

Use execute_script method on Capybara.

# run a script
page.execute_script("$('#n350071-frame').height(10)")

# then, test it.
within('n350071-frame') do
  expect(find('div.body').not_to have_selector('div.target')
end

The syntax is this.

execute_script(script, *args)

💚 one more tips: evaluate_script

If you need return value, please use evaluate_script. But, be careful, it might return complex jQuery object. So, you should use execute_script by default.

evaluate_script(script, *args)

注意: jQueryの複雑な戻り値が帰ってくる場合には、戻り値のないexecute_scriptがよい。

📚 Reference

Top comments (0)