capybara-webkitやseleniumなどのjavascript対応ドライバーを使用していると仮定して、Capybara内のCKEditor領域を埋めるにはどうすればよいですか?
4 に答える
ここで見つけたものから着想を得て、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!'
マークアンドレの素晴らしい答えへの小さな追加
同じページでネストされたフォームまたは複数のテキストエリアを使用している場合、生成された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'
私にとって、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とセレンドライバーの両方で動作します
この投稿に触発された
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