如何用webkit或selenium驱动程序填充capybara的ckeditor
假设我使用的是像capybara-webkit或selenium这样的javascript驱动程序,我怎样才能填充Capybara中的CKEditor区域?
Marc-André的一个很棒的补充
如果您在同一页面中使用嵌套表单或多个textareas生成的ID非常难看并且很难写入测试(例如person_translations_attributes_2_biography
), person_translations_attributes_2_biography
在他的方法中添加一小部分内容,您就可以使用标签而不是ID找到ckeditors
# 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'
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
对我来说, 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驱动程序
灵感来自这篇文章