Testing CodeMirror Editor with Capybara & RSpec

CodeMirror is a JavaScript text editor that I recently needed to test, but it was a little tricky getting that test automated with Capybara.

CodeMirror converts a given textarea into the editor field and hides the textarea which causes the test to have a tough time entering text into it.

See the fill_in_editor_field(text) method below for how you can enter text into CodeMirror in your feature specs, and the have_editor_display(options) method for how you can assert the editor is displaying the expected text:

# Important, `:js` metadata
# required for Capybara to run this
# using a driver for a
# JavaScript-capable browser.
feature '...', :js do

  scenario '...' do
    fill_in_editor_field "Hello World"
    expect(page).to have_editor_display text: "Hello World"


  def fill_in_editor_field(text)
    within ".CodeMirror" do
      # Click makes CodeMirror element active:

      # Find the hidden textarea:
      field = current_scope.find("textarea", visible: false)

      # Mimic user typing the text:
      field.send_keys text

  def have_editor_display(options)
    editor_display_locator = ".CodeMirror-code"
    have_css(editor_display_locator, options)

This solution has been tested in Chrome 54 on Mac OS X.

Published by Eliot Sykes

I help teams grow their Rails apps and themselves as a Rails consultant and coach for Rails developers.