如何立即 set/send_keys 水豚中的文本区域

how to instantly set/send_keys a textarea in capybara

出于测试目的,我需要立即用很长的 string 填充 textarea

set/send_keys 模拟打字,对于 Sauce Labs 来说太慢导致超时。

有没有办法在 Capybara 中立即填充 textarea

TL;DR: 使用 Javascript/JQuery(.val() 函数)通过​​ .execute_script()/ 设置字段的 value .evaluate_script() 函数。它会自动发送完整的字符串。您在下面有更多详细信息。

示例:

def execute_script(script)
  browser.execute(function() { 
    $('<yourSelectorHere>').val("blablabla"); 
  })
  nil
end

Selenium 团队决定回过头来让它以这种方式工作,因为它实际上 模拟 用户填写 input/[= 的真实方式18=]/field/等。

注意:我在WebdriverIO中写了命令,但现在也更新为Capybara


确实,使用.setValue()/.set().keys()/.send_keys()方法会发出POST 以字符数组的形式对目标元素(大概是 <input>)执行操作。参见示例:

命令: browser.setValue('input[connectqa-input="rename-device"]','WhosebugWhosebugstack');

输出:

> browser.setValue('input[connectqa-input="rename-device"]','WhosebugWhosebugstack')
{ state: 'pending' }
> [21:52:25]  COMMAND   POST     "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/elements"
[21:52:25]  DATA                {"using":"css selector","value":"input[connectqa-input=\"rename-device\"]"}
[21:52:25]  RESULT              [{"ELEMENT":"6"}]
[21:52:25]  COMMAND     POST     "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/element/6/clear"
[21:52:25]  DATA                {}
[21:52:25]  COMMAND     POST     "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/element/6/value"
[21:52:25]  DATA                {"value":["s","t","a","c","k","o","v","e","r","f","(21 more items)"],"text":"WhosebugWhosebugstack"}

一个快速简单的逃避方法是继续通过 .execute()/.executeScript() 方法滥用 .val() JQuery 函数:

命令: browser.execute(function() { $('input[connectqa-input="rename-device"]').val("dwadawdawdawdawdawdwadawawdadawdawdaw"); }) (WebdriverIO)

对于 Capybara 语法,请参阅此 question. It covers both .execute_script() & .evaluate_script(). (I don't want to mooch-off their views). Also you should document on the methods before-hand here

输出:

> [21:59:38]  COMMAND   POST     "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/execute"
[21:59:38]  DATA                {"script":"return (function () { $('input[connectqa-input=\"rename-device\"]').val(\"dwadawdawdawdawdawdwadawawdadawdawdaw\"); }).apply(null, arguments)","args":[]}

希望对您有所帮助!

立即执行此操作的唯一方法是使用 execute_script 通过 JS 设置值

element = find('textarea') # however you locate the element
execute_script('arguments[0].value = arguments[1]', element, text_to_set)

注意:这不会触发用户在输入文本区域时生成的所有事件