如何用webkit或selenium驱动程序填充capybara的ckeditor

Mar*_*une 20 selenium webkit ruby-on-rails ckeditor capybara

如果我使用像capybara-webkit或selenium这样的支持javascript的驱动程序,我如何填充Capybara中的CKEditor区域?

Mar*_*une 32

受到我在这里发现的启发,我想出了使用javascript来设置隐藏textareaCKEditor对象上的数据的解决方案.根据具体情况,似乎都不够.

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!'
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,它确实节省了我很多时间。一个小修正:在水豚 2.1.0 中,上面的 `browser.execute_script` 应该是 `page.execute_script`。 (2认同)

Fab*_*bio 10

Marc-André的一个很棒的补充

如果您在同一页面中使用嵌套表单或多个textareas生成的ID非常难看并且很难写入测试(例如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
Run Code Online (Sandbox Code Playgroud)

用这种方式代替了这一点

fill_in_ckeditor 'person_translations_attributes_2_biography', with: 'Some text'
Run Code Online (Sandbox Code Playgroud)

你可以写这个

fill_in_ckeditor 'Biography', with: 'Some text'
Run Code Online (Sandbox Code Playgroud)