Rails/Rspec/Capybara:解释执行脚本的 javascript 字符串的引号
Rails/Rspec/Capybara: Interpreting quotes for javascript string for execute script
考虑到我需要通过输入名称在水豚中使用 javascript 设置元素的选定索引...
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
将其解释为字符串的正确方法是什么,以便它可以在 Capybara 中使用 execute_script(function_name_string)
执行?因为我不断收到语法错误,所以不确定如何嵌套 " 和 ' 引号。
解决您问题的最简单方法是使用 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 采用选项字符串(你应该有 - 否则为什么首先要有一个 select 元素)
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
select_option
直接在选项元素上调用,可以通过多种方式找到,例如
find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option
考虑到我需要通过输入名称在水豚中使用 javascript 设置元素的选定索引...
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
将其解释为字符串的正确方法是什么,以便它可以在 Capybara 中使用 execute_script(function_name_string)
执行?因为我不断收到语法错误,所以不确定如何嵌套 " 和 ' 引号。
解决您问题的最简单方法是使用 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 采用选项字符串(你应该有 - 否则为什么首先要有一个 select 元素)
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
select_option
直接在选项元素上调用,可以通过多种方式找到,例如
find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option