20

capybara-webkitやseleniumなどのjavascript対応ドライバーを使用していると仮定して、Capybara内のCKEditor領域を埋めるにはどうすればよいですか?

4

4 に答える 4

33

ここで見つけたものから着想を得て、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!'
于 2012-06-09T02:14:51.297 に答える
11

マークアンドレの素晴らしい答えへの小さな追加

同じページでネストされたフォームまたは複数のテキストエリアを使用している場合、生成されたIDはかなり醜く、テストに書き込むのが困難です(たとえばperson_translations_attributes_2_biography)彼のメソッドにこの小さな追加を加えると、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の問題を参照してください

iframeコンテキストを変更しないckeditor入力を入力する別の方法を見つけました:

  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とセレンドライバーの両方で動作します

この投稿に触発された

于 2017-09-20T10:33:40.040 に答える
2

ckeditorインスタンスで動作するRSpec+Capybaraサポートファイル

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

https://gist.github.com/3308129

于 2012-08-09T21:55:29.977 に答える