[英]Rails/Rspec/Capybara: Interpreting quotes for javascript string for execute script
Given that I need to set an element's selected index with javascript in capybara by the input name... 鉴于我需要在capybara中使用输入名称通过javascript设置元素的选定索引...
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
What is the proper way to interpret this as a string so it can be executed in Capybara with execute_script(function_name_string)
? 将其解释为字符串的正确方法是什么,以便可以使用
execute_script(function_name_string)
在Capybara中执行它? Because I keep getting syntax errors, unsure how to nest the " and ' quotations. 因为我不断收到语法错误,所以不确定如何嵌套“和”引号。
Easiest solution to your question is to use a heredoc 最简单的解决方案是使用heredoc
page.execute_script <<~JS
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
JS
Although if you have need for the element for anything else it's probably nicer to find the element in ruby and then just call execute_script on the element 尽管如果您需要其他任何元素,最好在ruby中找到该元素,然后在该元素上调用execute_script
el = find("select[name='user[user_locations_attributes][0][location_attributes][state]']")
el.execute_script('this.selectedIndex = 50;')
As a related question - is there a reason you're doing this via JS rather than just clicking on the correct option? 作为一个相关问题-您是否有理由通过JS而不是仅单击正确的选项来执行此操作? If you're just scraping a page there's no issue, but if you're actually testing something this basically makes your test invalid since you could potentially be doing things a user couldn't
如果您只是在抓取页面,那没有问题,但是,如果您实际上正在测试某项内容,则基本上会使您的测试无效,因为您可能正在做用户无法做的事情
Since you commented that you are testing, you really shouldn't be doing this via JS, but should instead be using select
or select_option
. 由于您评论说您正在测试,因此您实际上不应该通过JS进行此操作,而应该使用
select
或select_option
。 select takes the options string (which you should have - otherwise why have a select element in the first place) select接受options字符串(您应该拥有-否则为什么要首先使用select元素)
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
select_option
is called on the option element directly, which can be found in a number of ways, such as 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.