假设我正在使用像 capybara-webkit 或 selenium 这样的支持 javascript 的驱动程序,我如何填充 Capybara 中的 CKEditor 区域?
问问题
3837 次
4 回答
33
受我在这里发现的启发,我想出了使用 javascript 将数据设置在隐藏对象textarea
和CKEditor
对象上的解决方案。两者似乎都不够,视情况而定。
def fill_in_ckeditor(locator, opts)
content = opts.fetch(:with).to_json # convert to a safe javascript string
page.execute_script <<-SCRIPT
CKEDITOR.instances['#{locator}'].setData(#{content});
$('textarea##{locator}').text(#{content});
SCRIPT
end
# Example:
fill_in_ckeditor 'email_body', :with => 'This is my message!'
于 2012-06-09T02:14:51.297 回答
11
Marc-André 精彩回答的一个小补充
person_translations_attributes_2_biography
如果您在同一页面中使用嵌套表单或多个文本区域,则生成的 ID 非常难看,并且很难通过对他的方法的这个小补充写入测试(例如),您可以使用它们的标签而不是 ID 来定位 ckeditor
# Used to fill ckeditor fields
# @param [String] locator label text for the textarea or textarea id
def fill_in_ckeditor(locator, params = {})
# Find out ckeditor id at runtime using its label
locator = find('label', text: locator)[:for] if page.has_css?('label', text: locator)
# Fill the editor content
page.execute_script <<-SCRIPT
var ckeditor = CKEDITOR.instances.#{locator}
ckeditor.setData('#{params[:with]}')
ckeditor.focus()
ckeditor.updateElement()
SCRIPT
end
以这种方式而不是这样
fill_in_ckeditor 'person_translations_attributes_2_biography', with: 'Some text'
你可以写这个
fill_in_ckeditor 'Biography', with: 'Some text'
于 2014-06-09T12:57:49.033 回答
3
对我来说,Marc-André 的回答在 webkit 驱动程序中切换 iframe 上下文。请参阅此 capybara-webkit 问题
我找到了另一种填充 ckeditor 输入的方法,它不会改变 iframe 上下文:
def fill_in_ckeditor(id, with:)
within_frame find("#cke_#{id} iframe") do
find('body').base.send_keys with
end
end
并称之为
fill_in_ckeditor 'comment', with: 'This is my message!'
适用于 webkit 和 selenium 驱动程序
于 2017-09-20T10:33:40.040 回答
2
RSpec + Capybara 支持文件与 ckeditor 实例一起使用
module Ckeditor
class Instance
attr_reader :capybara
private :capybara
def initialize(instance_id, capybara)
@instance_id, @capybara = instance_id, capybara
end
def val(value)
capybara.execute_script "jQuery('textarea##{@instance_id}').val('#{value}')"
end
def reload_all
capybara.execute_script "for(var instance in CKEDITOR.instances) { if(CKEDITOR.instances.hasOwnProperty(instance)) {CKEDITOR.instances[instance].destroy(true);} }"
capybara.execute_script "CKEDITOR.replaceAll();"
end
end
end
# usage
# rte = Ckeditor::Instance.new(:my_instance_id, page)
# rte.val 'foo'
# rte.reload_all
# NOTE: page is provided by Capybara
于 2012-08-09T21:55:29.977 回答