在Capybara,如何用包含标签的文本填写字段?

时间:2014-05-07 06:20:35

标签: ruby capybara capybara-webkit

我的每个场景都会读取文件中的示例并将其复制到文本字段中:

def sample(name)
  IO.read("spec/samples/#{name}.bib")
end

feature 'Import a record' do

  scenario 'from JabRef' do
    fill_in 'bibtex', :with => sample('jabref')
    in_dialog.click_button 'Import'
    ...
  end

end

这很好用,直到其中一个样本中有一个列表:当手动复制和粘贴工作时,测试失败。

从其他问题[1],我了解到将\t\n解释为键控输入应该是一个“功能”。有没有办法停用此功能并只是“粘贴”内容?

1 个答案:

答案 0 :(得分:1)

如果所有其他方法都失败了,您可以使用Javascript插入文字:

page.execute_script '$("#bibtex").val("' << sample('jabref') << '")'

如果你经常这样做,我会用辅助方法(fill_in_plain或类似方法)提取它,也许不使用jQuery的帮助(使用普通的旧Javascript,即document.getElementById等等。


这是一个正确的帮手,仍在使用jQuery:

module CapybaraWebkitWorkarounds

  def fill_in_plain(selector, with: nil)
    value = with.gsub '"', "\\\"" # poor man's escaping
    page.execute_script %Q{ $("#{selector}").val("#{value}") }
  end

end

RSpec.configure do |config|
  # make it available in all feature specs
  config.include CapybaraWebkitWorkarounds, type: :feature
end

然后,在您的功能规范中,您只需

feature 'Import a record' do

  scenario 'from JabRef' do
    fill_in_plain 'textarea[name="bibtex"]', with: sample('jabref')
    in_dialog.click_button 'Import'
    ...
  end

end

请注意,fill_in_plain助手现在只能理解jQuery选择器(即CSS选择器)字符串作为其第一个参数。