Search code examples
rubycapybaracapybara-webkit

In Capybara, how to fill in a field with a text containing a tab?


Each of my scenarios reads a sample in a file and copy them in a text field:

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

This worked fine, until one of the sample had a tabulation in it: while a manual copy and paste worked, the test failed.

From other questions [1], I have understood that interpreting \t and \n as keyed inputs is supposed to be a "feature". Is there a way to deactivate this feature and just "paste" the content?


Solution

  • If all else fails, you could insert your text using Javascript:

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

    If you do this often enough, I'd extract this in a helper method (fill_in_plain or similar), maybe without using the help of jQuery (using plain old Javascript, i.e. document.getElementById et cetera).


    Here's a proper helper, still using 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
    

    Then, in your feature spec, you'll do simply

    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
    

    Please note, that the fill_in_plain helper now only understands jQuery selector (i.e. CSS selectors) strings as its first argument.