Skip to content

Capybara UI Cheat Sheet

Joe Alba edited this page Mar 18, 2024 · 2 revisions

Different ways to accomplish basic Capybara-UI tasks. If something's missing, please add. If something's wrong, please fix. Thanks!

WIDGETS
by class
  widget :todo_item, '.todo-item'

by xpath
  widget :todo_item, [:xpath, '(//*[@class="todo_item"])[1]']

with proc
  widget :error, -> (text) { ['.alert-danger', text: text] }
  widget :link_to, -> (path, selector) { ["a#{selector}[href='#{path}']"] }

by root
  class TodoItem < Capybara::UI::Widget
    root '.todo-item'
  end

  class TodoItem < Capybara::UI::Widget
    root :xpath, '//some/node'
  end

html attributes
  <a href="/items/1" id="todo_item" class="todo-item right-aligned">
  widget(:todo_item).id #=> "todo_form"
  widget(:todo_item).classes #=> ["todo-item", "right-aligned"]
  widget(:todo_item).root['href'] #=> "/items/1"


FORMS
form :example_form, '.form-example' do
  text_field :text_widget, 'text_field_name'
  text_field :text_widget, ['.text-field-class']
  select :select_widget, 'select_field_name'
  check_box :check_box_widget, 'check_box_field_name'
  widget :generic_field, '.generic-field-class'
  # currently no support for radio buttons
end

submission
  submit :form_widget, changes
  submit :form_widget, field1: 'Value1', field2: 'Value2'
  widget(:form_widget).submit_with(changes)
  widget(:form_widget).submit_with(field1: 'Value1', field2: 'Value2')

field set without submission
  set :form_widget, params
  widget(:form_widget).set params

current values
  widget(:form).widget_name


TABLES
default declaration
  widget :todo_table, Capybara::UI::Table

custom declaration
  widget :todo_table, '.todo-table', Capybara::UI::Table do
    header_row '.header-row' do
      column 'span'
    end

    data_row '.data-row' do
      column 'span'
    end
  end

current values
  widget(:list_table).rows[0]
  widget(:list_table).columns[2]
  widget(:list_table).columns['Header Col Name']


DSL Macros
elements
  widget :widget_name
  list :list_name
  form :form_name

actions
  click :widget_name, '.widget-class'
  click :link_to, ['.my-link', '/home/path']
  hover :widget_name, '.widget-class'
  double_click :widget_name, '.widget-class'
  right_click :widget_name, '.widget-class'
  set :form_widget, <key-value-params>
  submit :form_widget, <key-value-params>


RSPEC METHODS
expect(role).to see :widget_name, '.widget-class'
Clone this wiki locally