簡體   English   中英

Rails / Rspec / Capybara:執行腳本的JavaScript字符串的引號

[英]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進行此操作,而應該使用selectselect_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM