[英]Rails/Rspec/Capybara: Interpreting quotes for javascript string for execute script
鉴于我需要在capybara中使用输入名称通过javascript设置元素的选定索引...
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
将其解释为字符串的正确方法是什么,以便可以使用execute_script(function_name_string)
在Capybara中执行它? 因为我不断收到语法错误,所以不确定如何嵌套“和”引号。
最简单的解决方案是使用heredoc
page.execute_script <<~JS
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
JS
尽管如果您需要其他任何元素,最好在ruby中找到该元素,然后在该元素上调用execute_script
el = find("select[name='user[user_locations_attributes][0][location_attributes][state]']")
el.execute_script('this.selectedIndex = 50;')
作为一个相关问题-您是否有理由通过JS而不是仅单击正确的选项来执行此操作? 如果您只是在抓取页面,那没有问题,但是,如果您实际上正在测试某项内容,则基本上会使您的测试无效,因为您可能正在做用户无法做的事情
由于您评论说您正在测试,因此您实际上不应该通过JS进行此操作,而应该使用select
或select_option
。 select接受options字符串(您应该拥有-否则为什么要首先使用select元素)
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
select_option
是直接在option元素上调用的,可以通过多种方式找到它,例如
find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.