Rails/Rspec/Capybara:为执行脚本解释javascript字符串的引号

Rails/Rspec/Capybara:为执行脚本解释javascript字符串的引号,javascript,ruby-on-rails,capybara,Javascript,Ruby On Rails,Capybara,假设我需要使用capybara中的javascript按输入名称设置元素的选定索引 var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50'; 将其解释为字符串的正确方法是什么,以便它可以在Capybara中通过execute\u脚本(function\u name\u str

假设我需要使用capybara中的javascript按输入名称设置元素的选定索引

var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';

将其解释为字符串的正确方法是什么,以便它可以在Capybara中通过
execute\u脚本(function\u name\u string)
执行?因为我经常遇到语法错误,不确定如何嵌套“and”引语。

解决问题的最简单方法是使用herdoc

page.execute_script <<~JS
  var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
JS
作为一个相关的问题-你通过JS这样做而不是点击正确的选项有什么原因吗?如果你只是在抓取一个页面,没有问题,但是如果你实际上在测试一些东西,这基本上会使你的测试无效,因为你可能在做一些用户无法做的事情

既然你评论说你正在测试,你真的不应该通过JS来做这件事,而是应该使用
select
select\u option
。select接受options字符串(你应该有这个字符串,否则为什么首先要有select元素)

select\u option
直接在option元素上调用,可以通过多种方式找到,例如

find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option

因为元素没有ID或任何易于识别的东西,所以我尝试只编写测试而不更改前端。顺便说一句,你不能执行el.execute_script你只能在页面上调用execute_script,所以我就这么做了。@zasman在Capybara 3.2中添加了对元素调用
execute_script
的功能,所以你可以显然,运行的是一个非常过时的版本。我还更新了我的答案,以显示两种方法,这两种方法在测试时比使用JS更好。如果这已经回答了您的问题,请不要忘记接受答案(复选标记)所以这个问题被标记为已回答。嗨,这是有意义的“gem”水豚、“2.6.2”谢谢你的帮助。
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option