A Page Object Model DSL for Capybara of ActiveAdmin, built on SitePrism.
System specs call semantic methods, such as table.row(id).cell(:name), filters.filter(:status).select_option("Active") or main_menu.go("Catalog", "Orders"), instead of CSS selectors. The selectors for vanilla ActiveAdmin 3 live in this gem.
- 1.x supports vanilla ActiveAdmin 3 (tested on 3.5.2). This is the
1-x-stablebranch. - 2.x supports vanilla ActiveAdmin 4. This is the
mainbranch. Its sections and methods have the same names as 1.x where the component exists in both versions.
To upgrade ActiveAdmin from 3 to 4, bump this gem to 2.x. Only specs that use a feature ActiveAdmin 4 removed need a change: Tabs, the action-item dropdown and UtilityNavigation raise RemovedInActiveAdmin4 in 2.x.
Until the first release, install it from git:
# Gemfile
group :test do
gem "active_admin_page_objects", github: "activeadmin-plugins/active_admin_page_objects", branch: "1-x-stable"
end# spec/rails_helper.rb, or a file in spec/support
require "active_admin_page_objects"Runtime dependencies: activeadmin (>= 3.0, < 4.0.0.a), site_prism (>= 5.0, < 7) and capybara (>= 3.37), on Ruby 3.3 or later. CI runs Ruby 3.3 and 3.4 with activeadmin 3.5.2, capybara 3.40 and site_prism 5.2 and 6.0; older versions inside these ranges are not tested.
RSpec.configure do |config|
# Rails 8 loads routes lazily. A first request to a literal URL then loads them inside the
# Capybara server thread, which breaks the Devise session lookup.
config.before(:suite) { Rails.application.reload_routes_unless_loaded }
endWrite one page class per ActiveAdmin page and declare the sections it uses:
class CustomerIndex < ActiveAdminPageObjects::Page
set_url "/admin/customers{?query*}"
section :table, ActiveAdminPageObjects::Table do
column :id, "Id"
column :name, "Name"
column :email, "Email"
end
section :filters, ActiveAdminPageObjects::Filters
section :scopes, ActiveAdminPageObjects::Scopes
section :pagination, ActiveAdminPageObjects::Pagination
section :batch_actions, ActiveAdminPageObjects::BatchActions
end
index = CustomerIndex.new
index.load
expect(index.table).to have_declared_columnsThe column lines declare the columns and the header labels that have_declared_columns checks. A section without them takes any key and has no label check: see Declared labels.
Every element and section also gets SitePrism's has_<name>? and has_no_<name>? predicates, so expect(index).to have_no_pagination works.
Use the has_no_* matchers (have_no_row), not not_to have_*. They wait for the condition and are the only correct form with a JavaScript driver.
ActiveAdminPageObjects::Page is a SitePrism::Page that includes ActiveAdminPageObjects::Layout. Include Layout into your own SitePrism::Page subclass if you already have one.
expect(page_object).to have_site_title(text: "My Admin")
expect(page_object).to have_page_title(text: "Customers")
expect(page_object).to have_blank_slate(text: "There are no Customers yet.")
page_object.panel("Notes").body # the panel titled "Notes"
page_object.sidebar("Help").body # the sidebar section titled "Help"
page_object.modal_dialog # see Batch actionsActiveAdmin 3 has no dark mode toggle and no user menu button. dark_mode_toggle (alias theme_switcher) and user_menu_button raise ActiveAdminPageObjects::NotInActiveAdmin3.
panel skips sidebar sections and the comments panel, which ActiveAdmin 3 renders as panels too. Use sidebar and Comments for them.
The current user and the logout link in the header.
navigation = page_object.utility_navigation
navigation.current_user # => "admin@example.com"
navigation.labels # => ["admin@example.com", "Logout"]
navigation.logoutexpect(page_object.breadcrumbs).to have_labels("Admin", "Customers")
expect(page_object.breadcrumbs).to have_no_labels("Admin")
page_object.breadcrumbs.labels # => ["Admin", "Customers"]
page_object.breadcrumbs.links # => Capybara elementslabels returns the text the driver reports. ActiveAdmin 3's CSS uppercases the trail, so a JavaScript driver gives ["ADMIN", "CUSTOMERS"]. The matchers ignore case.
page_object.action_items.labels # => ["New Customer", "More"]
page_object.action_items.click("New Customer")
expect(page_object.action_items).to have_item("More")ActiveAdmin 3 always renders the container, so assert on its items, not on the section.
A dropdown_menu is an item too. dropdown(label) returns a DropdownMenu (the only one when called without a label):
more = page_object.action_items.dropdown("More")
more.label # => "More"
more.labels # => ["Report", "Customers"], also from a closed menu
more.open
more.click("Customers") # opens the menu first
expect(more).to have_item("Report")ActiveAdmin 3 renders the notice, alert, error and warning types. It renders the container on every page, so assert on the content: have_no_flash works without flashes.
expect(page_object.flashes).to have_flash(:notice, "Customer was successfully created.")
expect(page_object.flashes).to have_no_flash(:error)
page_object.flashes.messages # every flash text
page_object.flashes.messages(:alert) # one typeItems are found by their label path, case-insensitively. href returns the link's URL as the driver reports it, which is the absolute URL in a browser. have_item(..., href:) takes a path, a full URL or a Regexp, and compares a path to the URL's path and query. go reads the link's URL and visits it, so it works with closed submenus and under rack_test. click drives the menu as a user does: it hovers each parent, then clicks the item's link. It sees visible items only, so a hidden or unreachable submenu raises Capybara::ElementNotFound. Under rack_test, which cannot hover, it skips the hovering.
page_object.main_menu.go("Customers")
page_object.main_menu.go("Catalog", "Orders")
page_object.main_menu.click("Catalog", "Orders")
expect(page_object.main_menu).to have_item("Catalog", "Categories")
expect(page_object.main_menu).to have_item("Catalog", "Orders", href: "/admin/orders")
page_object.main_menu.href("Catalog", "Orders") # => "http://127.0.0.1:3000/admin/orders" in a browser
page_object.main_menu.current_labels # => ["Catalog", "Orders"]
page_object.main_menu.labels("Catalog") # => ["Categories", "Orders"]Cells are keyed by column: :external_id or "External ID" both match the col-external_id class. have_header_names takes every header in order and compares case-insensitively, so "Id" and "ID" match. To check the exact labels, declare the columns: see Declared labels.
table = index.table
expect(table).to have_header_names("ID", "NAME", "EMAIL")
expect(table).to have_rows(count: 2)
table.header_names # as the driver reports them
table.column_keys # => ["id", "name", "email"]
row = table.row(customer.id)
row.record_id # => "42"
expect(row).to have_cell(:name, exact_text: "Acme")
expect(row).to have_no_cell(:email, text: "old@example.com")
row.cell(:email) # the <td>
row.select # ticks the batch-action checkbox
row.status_tag(:status) # see Status tags
table.rows.map(&:record_id)
expect(table).to have_row(customer.id) # by record id
expect(table).to have_no_row(deleted.id)
table.row_with(:server, "10.0.0.1:7080") # by a cell's whole text; a Regexp matches part of it
expect(table).to have_row_with(:status, "Failed")row_with, have_row_with and have_no_row_with find rows that have no record id, such as a table_for of plain values. row, have_row and have_no_row take the record id: an Integer or a non-empty String. Anything else, such as the record itself or nil, raises ArgumentError.
Sorting reads and clicks the header links:
table.sort_by(:name) # one click
table.sort_by(:name, :asc) # clicks until the column is sorted that way
table.sorted_by # => ["name", :asc], or nil
expect(table).to have_sortable_column(:name)The first click on an unsorted column sorts descending.
The section defaults to table.index_table. Pass a locator for another table, such as a table_for inside a panel: section :orders, ActiveAdminPageObjects::Table, "#orders_panel table".
Rows are keyed by the row :foo symbol, or by the label parameterized with _.
table = show.attributes_table
expect(table).to have_row(:name, exact_text: "Acme")
expect(table).to have_no_row(:secret)
table.row(:category) # the <tr>
table.value(:email) # => "acme@example.com"
table.status_tag(:status) # see Status tagsAn index row and the attributes table of a show page match the status tag of a cell by its label and, with type:, its CSS classes:
expect(index.table.row(customer.id)).to have_status_tag(:status, "Pending")
expect(show.attributes_table).to have_status_tag(:status, "Pending", type: "pending")
expect(show.attributes_table).to have_no_status_tag(:status, "Active")status_tag(key) returns the StatusTag:
tag = show.attributes_table.status_tag(:status)
tag.label # => "Pending"
tag.type # => "pending", or "ok warning" for several classes
expect(tag).to have_type("pending")
expect(tag).to have_label("pending")label returns the DOM text. ActiveAdmin 3's CSS uppercases it on screen. The matchers ignore the case of the label.
A cell may hold several status tags. have_status_tag passes when any of them matches, and have_no_status_tag when none does. status_tag(key) raises Capybara::Ambiguous for such a cell: use status_tags(key).
expect(row).to have_status_tag(:flags, "Archived", type: "warning")
row.status_tags(:flags).map(&:label) # => ["Draft", "Archived"]class CustomerShow < ActiveAdminPageObjects::Page
set_url "/admin/customers/{id}"
section :attributes_table, ActiveAdminPageObjects::AttributesTable
section :notes, ActiveAdminPageObjects::Panel, :active_admin_panel, "Notes"
end
show.notes.title # => "Notes"
expect(show.notes.body).to have_text("Pays late")
show.notes.links # => [{ text: "Invoices", href: "/admin/invoices?customer=1" }]A sidebar section works the same way, with ActiveAdminPageObjects::Sidebar and the :active_admin_sidebar selector: section :help, ActiveAdminPageObjects::Sidebar, :active_admin_sidebar, "Help".
links lists the links of the body, each with its text and its href attribute as the page wrote it, on every driver.
A String title is the whole title, ignoring case. For a title with a changing part, such as "Possible Routes (2)", pass a Regexp, which is case-sensitive unless it has /i. It works for page.panel, page.sidebar and both selectors:
section :routes, ActiveAdminPageObjects::Panel, :active_admin_panel, /\APossible Routes \(\d+\)\z/
show.panel(/\APossible Routes/).title # => "Possible Routes (2)"
show.sidebar(/\AVersions/)class CustomerShow < ActiveAdminPageObjects::Page
set_url "/admin/customers/{id}"
section :comments, ActiveAdminPageObjects::Comments
end
comments = show.comments
comments.add("Called back")
expect(comments).to have_comment("Called back")
comments.count # => 1, from the "Comments (1)" title
comments.bodies # => ["Called back"]
comments.authors # => ["admin@example.com"]
comments.delete("Called back") # accepts the browser confirmationfilter(key) returns the section typed by the filter input: StringFilter, NumericFilter, SelectFilter, BooleanFilter or DateRangeFilter. The key is the one given to filter :key; the section wraps #q_<key>_input. Filters that declare their filters take the declared name. A filter whose key holds its predicate, such as filter :uuid_eq, has a bare input and no predicate select: fill_in(with:) and have_value work, and a predicate: raises.
filters = index.filters
filters.filter(:name).fill_in(with: "Acme", predicate: "Equals") # or predicate: :eq
filters.filter(:balance).fill_in(with: 100, predicate: :gt)
filters.filter(:status).select_option("Active")
filters.filter(:active).set(true) # false, or nil for "Any"
filters.filter(:created_at).set("2026-01-01", Date.new(2026, 1, 31))
filters.submit
filters.clear # needs a JavaScript driver
expect(filters.filter(:name)).to have_value("Acme", predicate: "Equals")
expect(filters.filter(:status)).to have_selected("Active")
expect(filters.filter(:active)).to have_value(true)
expect(filters.filter(:created_at)).to have_range("2026-01-01", "2026-01-31")DateRangeFilter types the dates into the two inputs. It does not use the jQuery UI datepicker. set takes Date objects or ISO strings; nil or "" clears that end.
Declare one filter directly when a page uses it often:
section :name_filter, ActiveAdminPageObjects::StringFilter, "#q_name_input"
section :filters_footer, ActiveAdminPageObjects::FiltersFooter # submit and clearSelectFilter drives a visible native <select>. One that is hidden or marked aria-hidden="true", as a JavaScript select widget leaves it, raises Capybara::ElementNotFound: see Hidden selects.
customer = filters.filter(:customer)
customer.select_option("Acme")
expect(customer).to have_option("Acme")
expect(customer).to have_selected("Acme")
expect(customer).to have_item("Acme") # the chosen item, before submit
expect(customer).to have_disabled
expect(customer).to have_no_option("Globex")index.scopes.labels # => ["All", "Active"]
index.scopes.select("Active")
expect(index.scopes).to have_selected("Active")
index.scopes.count("Active") # => 12, or nil without a countActiveAdmin renders pagination only when there is more than one page.
index.pagination.go_to(3)
index.pagination.next_page
index.pagination.previous_page
expect(index.pagination).to have_current_page(2)
index.pagination.current_page # => 2The "Download: CSV XML JSON" links under the index table. ActiveAdmin renders them only when the index has records. A format is named by its link text, ignoring case.
links = index.download_links # section :download_links, ActiveAdminPageObjects::DownloadLinks
links.formats # => ["CSV", "XML", "JSON"]
expect(links).to have_format("CSV")
expect(links).to have_no_format("PDF")
links.href(:csv) # => "/admin/customers.csv", the attribute as written
links.click(:csv)Under rack_test, click loads the file: read it from page.body. A JavaScript driver downloads a CSV file as the browser does and stays on the page.
Actions are found by label ("Delete Selected") or by name (:destroy). apply(label, inputs = {}) opens the menu and clicks the action. An action with confirm: or form: opens ActiveAdmin's modal dialog: apply sets each of inputs by field name and clicks OK.
index.table.row(customer.id).select
index.batch_actions.select_all
index.batch_actions.apply(:destroy)
index.batch_actions.apply("Set Status Selected", status: "pending")
expect(index.batch_actions).to have_action("Flag Selected")page.modal_dialog is the dialog ActiveAdmin opens for batch actions. Use it to drive the dialog yourself, for example to cancel:
dialog = index.modal_dialog
dialog.title # => "Are you sure you want to do this?"
dialog.fill("status", with: "pending") # input or select, by field name
expect(dialog).to have_field("status")
dialog.confirm # or dialog.cancel
expect(index).to have_no_modal_dialogFields are named by attribute, as in f.input :email. A form that declares its fields takes the declared names.
form = form_page.form # section :form, ActiveAdminPageObjects::Form
form.field(:email).fill("acme@example.com")
form.fill(name: "Acme", category: "Retail", active: false) # in this order
form.submitfield(name) returns the section typed by the formtastic input class. fill(value) sets the field the way its type needs.
Form::StringFieldforstring,email,url,phone,password,numberandtext:filltypes the value.value.Form::SelectFieldforselect:fillpicks the option with that label.options(without the blank option) andselected. The<select>is visible: see Hidden selects.Form::BooleanFieldforboolean:fill(true)ticks the checkbox andfill(false)unticks it.checked?.Form::RadioFieldforradio:fillpicks the radio button with that label.optionsandselected.Form::CheckBoxesFieldforcheck_boxes:filltakes an array of labels, ticks them and unticks the others.check(*labels),uncheck(*labels)andchecked.Form::DatePickerFieldfordatepicker:filltakes a Date or a string and types it in. It does not use the jQuery UI datepicker.Form::FileFieldforfile:filltakes the path of the file and attaches it. A JavaScript driver needs an absolute path.Form::Fieldfor any other class:filltypes text, picks a select option or ticks a checkbox, by what the wrapper holds.
Every field also has errors, disabled?, enabled?, required? and input, the field's first control, and choose(option) for a select or a radio button. force_fill(text) sets a text control's value with JavaScript, past its maxlength, so a spec reaches the server's own check.
form.field(:status).options # => ["active", "pending", "closed"]
form.field(:status).selected # => "pending", or nil for the blank option
expect(form.field(:active)).to be_checked
form.field(:tier).selected # => "Gold", the chosen radio button
form.field(:channels).fill(%w[Email Post])
form.field(:channels).checked # => ["Email", "Post"]
form.field(:signed_on).fill(Date.new(2026, 1, 31))
form.field(:contract).fill(Rails.root.join("spec/fixtures/contract.pdf"))expect(form).to have_disabled_field(:code)
expect(form).to have_enabled_field(:name)
expect(form).to have_no_disabled_field(:name)
form.field(:code).disabled? # => true, without waiting- A field is disabled when every control in it is: the input, the select, or each radio button or checkbox of a field with choices. It is enabled when a control is not disabled. Hidden inputs do not count.
have_no_disabled_fieldandhave_no_enabled_fieldalso pass when the form has no such field.- The matchers wait, and take
visible:likefield. A has_many fieldset has them too.
expect(form).to have_field_error(:email, "is invalid") # the inline error contains the text
expect(form).to have_no_field_error(:name)
expect(form).to have_field_errors # any inline error
expect(form).to have_no_field_errors
expect(form).to have_exact_field_errors(name: "can't be blank", email: ["is invalid"])
form.field(:email).errors # => ["is invalid"]
expect(form).to have_semantic_errors("Name is reserved") # every message is shown; ignores case
expect(form).to have_semantic_errors(/can't be blank/) # a Regexp matches part of a message
expect(form).to have_exact_semantic_errors("Name is reserved", "Balance is negative")
expect(form).to have_exact_semantic_errors("Name is reserved", "Balance is negative", strict_order: true)
form.semantic_errors # => ["Name is reserved", "Balance is negative"]have_field_errorsandhave_no_field_errorslook at the whole form, has_many fieldsets included.have_exact_field_errorstakes each field with its message, or an array of messages. Every one of these fields shows exactly these messages, and no other field shows an error. Without arguments it passes when no field shows an error. It leaves out the fields of has_many fieldsets: ask each fieldset. Its keywords are field names, so it takes no Capybara options and novisible:. See Hidden elements.have_exact_semantic_errorscompares the base errors exactly and case-sensitively: the same messages, in any order.strict_order: truecompares the order too. Without messages it passes when the form shows no base error.have_no_exact_field_errorsandhave_no_exact_semantic_errorswait until the errors differ.
form.has_many(association) returns a HasMany for a has_many block. Fieldsets are 0-based. A fieldset has the field methods of the form: field, fill and the field error matchers.
orders = form.has_many(:orders)
orders.heading # => "Orders"
orders.count # => 2
expect(orders).to have_fieldsets(count: 2)
fieldset = orders.add # clicks the add link, returns the new fieldset
fieldset.fill(reference: "REF-NEW", state: "shipped")
orders.fieldset(0).field(:quantity).value # => "2"
expect(orders.fieldset(0)).to have_exact_field_errors(quantity: "must be greater than 0")
orders.remove(2) # a new fieldset: its remove link
orders.remove(0) # a saved one: ticks its delete checkbox
expect(orders.fieldset(0)).to be_marked_for_destroyDeclare the block on the form to declare the fields of its fieldsets: see Declared has_many blocks.
class CustomerShow < ActiveAdminPageObjects::Page
section :tabs, ActiveAdminPageObjects::Tabs
end
show.tabs.labels # => ["Overview", "Orders"]
show.tabs.switch("Orders")
show.tabs.current # => "Orders", or nil before jQuery UI sets the tabs up
expect(show.tabs.body).to have_text("Order list")
expect(show.tabs).to have_tab("Orders")A String is the whole label, ignoring case. switch, have_tab and have_no_tab also take a Regexp, case-sensitive unless it has /i, for a label with a changing part: show.tabs.switch(/\AOrders \(\d+\)\z/).
Sections find elements by key, so row(:external_id) passes whatever its label says. Declare each element with its label on the section, then check all of them with one matcher.
class CustomerIndex < ActiveAdminPageObjects::Page
set_url "/admin/customers{?query*}"
section :table, ActiveAdminPageObjects::Table do
column :selectable, ""
column :id, "Id"
column :external_id, "External ID"
column :actions, ""
end
section :filters, ActiveAdminPageObjects::Filters do
filter :external_id, "External ID", ActiveAdminPageObjects::StringFilter
filter :balance, "Balance", ActiveAdminPageObjects::NumericFilter
end
end
class CustomerShow < ActiveAdminPageObjects::Page
set_url "/admin/customers/{id}"
section :attributes_table, ActiveAdminPageObjects::AttributesTable do
row :email, "Email"
row :external_id, "External ID"
end
end
class CustomerForm < ActiveAdminPageObjects::Page
set_url "/admin/customers{/id}{/action}"
section :form, ActiveAdminPageObjects::Form do
field :email, "Email", ActiveAdminPageObjects::Form::StringField
field :status, "Status", ActiveAdminPageObjects::Form::SelectField
end
end
expect(index.table).to have_exact_columns
expect(index.filters).to have_exact_filters
expect(show.attributes_table).to have_exact_rows
expect(form_page.form).to have_exact_fieldsrow(key, label)andcolumn(key, label)need the label. An untitled column takes"": the selection column is:selectableand the actions column is:actions.filter(name, label, type)andfield(name, label, type)need the label and the section class.- Each takes
visible:for an element that may be hidden: see Hidden elements.
SitePrism 5 and 6 turn the block into a subclass of the section class. A named subclass takes the same lines in its class body. A subclass inherits the declarations of its superclass and adds its own.
A declaration defines no method on the section, so any name is valid, including name and title. Reach an element with filter(name), field(name) or has_many(name):
index.filters.filter(:balance).fill_in(with: 100, predicate: :gt)
form_page.form.field(:status).fill("pending")The name is the formtastic attribute or the ActiveAdmin filter key, and the only key: field :id, "Gateway", ActiveAdminPageObjects::Form::SelectField is reached with field(:id), has_field_error?(:id) and fill(id: ...). A subclass can declare an inherited name again.
For shortcuts, write your own methods in the section block.
filters.filter(name) and form.field(name) return an instance of the declared class. To use your own field or filter class, declare it. It is a subclass of the gem's class for that input:
class Select2Field < ActiveAdminPageObjects::Form::SelectField
# drives the widget: see Hidden selects below
end
section :form, ActiveAdminPageObjects::Form do
field :id, "Gateway", Select2Field
endThe declared class must be the class the gem detects for the wrapper, or a subclass of it. Otherwise the lookup raises ActiveAdminPageObjects::DeclaredClassMismatch, a Capybara::ExpectationNotMet, and the message names both classes. have_disabled_field and have_enabled_field raise it too.
Two of the gem's classes are subclasses of another detected class, so the check takes them for the parent's input: Form::DatePickerField on a string input, and BooleanFilter on a select filter.
The gem detects its classes by the formtastic class of the wrapper, and returns Form::Field or Filter for any other input. A theme or plugin adds its own input to that list: see Registered input classes. A section without declarations returns the detected class.
Hidden selects
SelectFilter, BooleanFilter, Form::SelectField, Form::Field and the predicate select of StringFilter and NumericFilter find the native <select> as Capybara finds elements by default, and leave out a select marked aria-hidden="true". When it is hidden or marked so, as a JavaScript select widget such as select2 leaves it, picking and reading raise Capybara::ElementNotFound: select_option, fill, selected, options, have_selected, have_option, have_item, have_disabled and their have_no_ forms. A page object that declares SelectFilter on a widget fails, and does not drive the select behind the widget.
For a widget, declare your own class. Override the method that picks, to drive the widget, and the private native_select_visibility, to read the select the widget hides:
class Select2Filter < ActiveAdminPageObjects::SelectFilter
def select_option(label)
find(".select2-selection").click
# select2 appends the dropdown to <body>, outside the filter.
root_element.session.find(".select2-results__option", exact_text: label).click
end
private
def native_select_visibility
:all
end
end
section :filters, ActiveAdminPageObjects::Filters do
filter :customer, "Customer", Select2Filter
end
filters.filter(:customer).select_option("Acme") # clicks the widget
expect(filters.filter(:customer)).to have_selected("Acme") # reads the hidden <select>native_select_visibilityreturns the Capybaravisible:value of every lookup of the native<select>::all,:hidden,:visible,trueorfalse. The default isnil: novisible:, soCapybara.ignore_hidden_elementsdecides.- A lookup of visible elements also leaves out a select marked
aria-hidden="true", on every driver. select2 clips its select to one pixel, which Cuprite reports as visible, and marks itaria-hidden.:alltakes that select too. - With
:allthe inherited methods pick from the hidden select and read it. Override the ones that have to go through the widget. - A
Form::SelectFieldsubclass overridesfillthe same way.
has_many(name, heading, &block) declares a has_many block of a form. form.has_many(:gateways) returns the HasMany. The block declares the fields of a fieldset, by the same rules.
section :form, ActiveAdminPageObjects::Form do
field :email, "Email", ActiveAdminPageObjects::Form::StringField
has_many :gateways, "Gateways" do
field :id, "Gateway", ActiveAdminPageObjects::Form::SelectField
end
def add_gateway(name) = has_many(:gateways).add.field(:id).fill(name)
end
form.has_many(:gateways).add.field(:id) # the SelectField of the new fieldset
form.has_many(:gateways).fieldset(0).field(:id).selected
expect(form.has_many(:gateways)).to have_fieldsets(count: 2)
expect(form.has_many(:gateways).fieldsets).to all(have_exact_fields)fieldsets reads the page once, and all passes on an empty list, so check the count first.
headingis the text of the block'sh3. The form's label matchers compare it. Passnilwhen the form usesheading: false.nameis the association.- A form that declares has_many blocks raises
ArgumentErrorfromhas_many(association)for any other association.
have_declared_columns, have_declared_filters, have_declared_rows and have_declared_fields pass when every declared element is on the page with exactly its label. The comparison is exact and case-sensitive, so "External id" does not match "External ID". Only whitespace is normalized.
- CSS
text-transformdoes not change the result, on any driver. - In filter and form labels, the text of links, buttons and
abbrelements is not part of the label. That drops the required marker (*) and controls that plugins append, such as the date range preset's "Set range" link. have_declared_fieldson a form also compares the headings of the declared has_many blocks. The fields of a fieldset are compared on the fieldset.- The order is not checked. Elements that are on the page but not declared are ignored: the exact matchers catch those.
- They wait like the other matchers.
have_no_declared_columnsand the other three wait until a label differs. - They raise
ArgumentErroron a section that declares nothing.
have_exact_columns, have_exact_filters, have_exact_rows and have_exact_fields pass when the label matcher passes and the page has no other element of that kind:
- Rows: the
tr.row-*of the attributes table. - Columns: the
th.col-*of the table, the untitled selection and actions columns included. - Filters: the filter wrappers of the filter form.
- Form fields: the input wrappers outside the has_many blocks, and each has_many block.
as: :hiddeninputs are not fields. - Fieldset fields: the input wrappers of the fieldset. The delete checkbox and a has_many block nested in the fieldset are left out.
Only visible elements count: see Hidden elements.
have_no_exact_columns and the other three wait until the page differs.
The label matchers and the exact matchers take only: and except:: a declared name, or an array of them. A name that is not declared raises ArgumentError.
expect(index.table).to have_exact_columns(except: :notes) # a column that only some users see
expect(form_page.form).to have_declared_fields(only: %i[email status])only:checks these elements and ignores the rest of the page, so no element is unexpected.except:skips these elements: the page may have them or not.- A scope that leaves no declared name, such as
only: [], raisesArgumentError: it would pass on any page.
Hidden elements
Lookups and matchers see only visible elements, as Capybara does by default. A hidden field, filter, row, column or has_many block is not found. The label matchers report it as missing, and the exact matchers do not count it as unexpected.
Pass visible: :all to a call to take hidden elements too:
form.field(:notes, visible: :all)
form.has_many(:orders, visible: :all)
filters.filter(:email, visible: :all)
show.attributes_table.row(:email, visible: :all)
show.attributes_table.value(:email, visible: :all)
index.table.row(customer.id).cell(:email, visible: :all)
expect(form).to have_field_error(:email, "is invalid", visible: :all)
expect(form).to have_exact_fields(visible: :all)
form.exact_mismatches(visible: :all)Or declare the element with visible: :all, for example a field that a script hides and shows:
section :form, ActiveAdminPageObjects::Form do
field :email, "Email", ActiveAdminPageObjects::Form::StringField
field :notes, "Notes", ActiveAdminPageObjects::Form::StringField, visible: :all
end
form.field(:notes) # found when it is hidden too
expect(form).to have_exact_fields # passes with the notes field hidden or shownrow,column,filter,fieldandhas_manytakevisible:. Every lookup and matcher then finds that element with it.visible:on a call overrides the declaration:form.field(:notes, visible: :visible). It takes Capybara's values::all,:hidden,:visible,trueandfalse.- On a matcher,
visible:applies to every element: the declared ones and the ones that are not declared. have_exact_field_errorshas novisible:option, because its keywords are field names. It counts the errors of the visible fields and of the fields declared withvisible:.value(key, visible: :all)returns the DOM text: a hidden cell has no visible text.visible:finds the element itself. A section still looks for its own controls as Capybara does by default, sofillandvalueof a hidden text field raiseCapybara::ElementNotFound.- The
<select>inside a visible field or filter is a control like any other: hidden or markedaria-hidden="true", as a JavaScript select widget leaves it, it is not found. See Hidden selects.
RSpec's own have_ matcher only reports that the predicate returned false. Include ActiveAdminPageObjects::RSpec::Matchers to get a message that lists what differs:
require "active_admin_page_objects/rspec"
RSpec.configure do |config|
config.include ActiveAdminPageObjects::RSpec::Matchers
end
expect(show.attributes_table).to have_exact_rows(except: :notes)active_admin_page_objects/rspec requires rspec/expectations. The gem does not depend on it: your suite's rspec or rspec-rails provides it.
expected exactly the declared rows (except: notes), but:
missing: secret
unexpected: email, status
label of external_id: expected "External id", got "External ID"
- The module defines
have_declared_rows,have_declared_columns,have_declared_filters,have_declared_fields,have_exact_rows,have_exact_columns,have_exact_filters,have_exact_fieldsand thehave_no_form of each. They call the same predicates with the same options, so specs need no change. missinglists the declared names the page lacks.unexpectedlists the elements on the page that are not declared; only the exact matchers have it. Eachlabel ofline gives the declared label and the label found.- The message names the
only:,except:andvisible:options given. - A
have_no_matcher that fails has nothing to list:expected the rows to differ from the declared ones, but they match exactly. not_to have_exact_rowscallshas_no_exact_rows?, so it waits for the page to differ.- On an object that declares nothing, each one is RSpec's predicate matcher.
The module also defines have_exact_field_errors, have_exact_semantic_errors and their have_no_ forms, for a form and for a has_many fieldset:
expect(form).to have_exact_field_errors(name: "is reserved", notes: "is too long")
expect(form).to have_exact_semantic_errors("Balance is negative", "Name is reserved", strict_order: true)expected exactly the given field errors, but:
name: missing "is reserved"; unexpected "can't be blank"
notes: missing "is too long"
email: unexpected "is invalid"
expected exactly the given semantic errors, in order, but:
order: expected "Balance is negative", "Name is reserved", got "Name is reserved", "Balance is negative"
- Field errors have one line per field that differs.
missinglists the expected messages the field does not show.unexpectedlists the messages it shows that were not expected. A field that was not expected has onlyunexpected. - Semantic errors have a
missingand anunexpectedline. Withstrict_order: trueand the same messages in another order, theorderline gives both orders. - Without arguments the message starts with
expected no field errorsorexpected no semantic errors. - A
have_no_matcher that fails says that the errors match exactly, or that the form shows no error when no arguments were given.
The module also defines the matchers shared with capybara_active_admin. Include it after that gem's matchers.
Without the module, ask the section what differs:
index.table.declared_label_mismatches # => { "external_id" => "External Id", "secret" => nil }
index.table.exact_mismatches
# => { missing: ["secret"], unexpected: ["email"], labels: { "external_id" => "External Id" } }declared_label_mismatches returns each failing name with the label found, or nil when the page has no such element. exact_mismatches splits them into missing and labels, and adds unexpected: the keys of the elements on the page that are not declared. Both take only:, except: and visible:.
last_mismatches returns what the last label or exact matcher found on its last try, in the form of exact_mismatches. last_field_errors and last_semantic_errors return the errors the last have_exact_field_errors or have_exact_semantic_errors found.
A section that declares anything raises ArgumentError for every other name, before it queries the page. Form#has_many is the exception: it checks the name only when the form declares has_many blocks. The message gives the name and lists the declared ones. A section without declarations takes any key, as before.
AttributesTable:has_row?,has_no_row?,row,value,status_tag,status_tags,has_status_tag?andhas_no_status_tag?.Table:sort_byandhas_sortable_column?. Its rows:cell,has_cell?,has_no_cell?,status_tag,status_tags,has_status_tag?andhas_no_status_tag?.Filters:filter.Formand the fieldsets of a declared has_many:field,fill,has_field_error?,has_no_field_error?,has_exact_field_errors?,has_no_exact_field_errors?,has_disabled_field?,has_enabled_field?and theirhas_no_forms.
Filters and fields take the declared name: form.field(:id) and have_field_error(:id).
Names compare as everywhere else: :external_id, "external_id" and "External ID" are the same name.
capybara_active_admin defines RSpec matchers for Capybara's page, such as have_page_title, have_table and have_status_tag. In an example group that includes them, they replace the predicate matchers of the page objects: expect(index).to have_page_title(text: "Customers") calls the matcher of that gem.
ActiveAdminPageObjects::RSpec::Matchers defines the same names for both. Include it after capybara_active_admin's matchers, so it takes precedence. The module also gives the label and exact matchers their failure messages.
require "capybara/active_admin/rspec" # includes that gem's matchers
require "active_admin_page_objects/rspec"
RSpec.configure do |config|
config.include ActiveAdminPageObjects::RSpec::Matchers
end- On a SitePrism page or section that has the predicate, such as
has_page_title?, the matcher calls it, like RSpec's ownhave_matchers. Negated, it callshas_no_page_title?when the object has it. - Capybara's own
has_table?does not count as such a predicate.have_tablecalls the page object only when it defineshas_table?itself, as a page withsection :tabledoes. - On anything else, such as Capybara's
page, it is the matcher of the module included before.
It covers the matchers of capybara_active_admin 1.0.0: have_action_item, have_action_item_link, have_attribute_row, have_attributes_table, have_batch_action, have_fields_date_range, have_flash_message, have_footer, have_form_error, have_has_many_fields_for, have_no_form_errors, have_page_title, have_panel, have_semantic_error, have_semantic_errors, have_sidebar, have_status_tag, have_submit_input, have_table, have_table_cell, have_table_header, have_table_row, have_table_scope and have_table_scopes.
These need a JavaScript driver such as Cuprite or Selenium:
BatchActions#applyandModalDialog: ActiveAdmin's JavaScript opens the menu and the dialog and submits the form.Filters#clearandFiltersFooter#clear: the "Clear Filters" link ishref="#".Tabs#switchandTabs#current: jQuery UI switches the tabs. Without JavaScript every tab body is shown.DropdownMenu#openand#click: the button toggles the menu. Without JavaScript the list is always shown.HasMany#addand#remove: the JavaScript adds and removes the fieldsets.Comments#delete: the link asks the browser to confirm.StringFilter#fill_inandNumericFilter#fill_inwith a predicate other than the selected one: the JavaScript renames the input when the predicate changes.Form::Field#force_fill: it sets the value with a script.
Everything else works with rack_test too, including MainMenu#go and MainMenu#click (without hovering), filters with the current predicate, plain selects, date ranges, scopes, pagination, sorting and forms.
Sections resolve their selectors when Capybara runs the query, through the :active_admin Capybara selector: find(:active_admin, :table). Requiring the gem before ActiveAdmin loads is safe.
Subclass a section, or include a module into one:
module TruncatedCells
def truncated_text(key)
cell(key).find(".truncate-text").text
end
end
ActiveAdminPageObjects::Table::Row.include(TruncatedCells)
class StatusPanel < ActiveAdminPageObjects::Panel
def status = body.find(".status").text
endBase your own sections on ActiveAdminPageObjects::Section to get selector_key, which points the default locator at a selector-map entry, and to share the map with the gem:
ActiveAdminPageObjects.register_selectors(audit_panel: "[data-audit-panel]")
class AuditPanel < ActiveAdminPageObjects::Section
selector_key :audit_panel
endregister_selectors also replaces a key of the gem, for example a theme's own main_menu.
Add a section or an element to every page that includes Layout, including page classes defined earlier:
ActiveAdminPageObjects::Layout.add_section(:audit_panel, AuditPanel)
ActiveAdminPageObjects::Layout.add_element(:banner, ".banner")To use your own field or filter class, declare it on the section: field :id, "Gateway", Select2Field. It is a subclass of the gem's class for that input, or of ActiveAdminPageObjects::Form::Field or ActiveAdminPageObjects::Filter for an input class the gem has no class for. See Declared types.
A theme or plugin whose input renders its own formtastic class, such as as: :searchable_select, registers the class that drives it. form.field and filters.filter then return it without a declaration:
ActiveAdminPageObjects.register_field_class("searchable_select", MyWidget::Field)
ActiveAdminPageObjects.register_filter_class("searchable_select", MyWidget::Filter)The field class is a subclass of ActiveAdminPageObjects::Form::Field and the filter class of ActiveAdminPageObjects::Filter; anything else raises ArgumentError. A registered class wins over the gem's class when the wrapper also carries a class the gem knows, such as select. A page object that declares the gem's class for a registered input raises DeclaredClassMismatch; declare the registered class or a subclass of it.
ActiveAdminPageObjects::SelectControl drives a visible native <select> for SelectFilter and Form::Field. For a widget on some selects, declare your own class: see Hidden selects. A gem that renders a JavaScript select widget for every select prepends a module into SelectControl instead. It overrides the private methods choose_option(scope, label), option_offered?(scope, label), control_disabled?(scope) and chosen_item?(scope, label), and native_select_visibility for the methods that still read the hidden <select>:
module MyWidget
module SelectControl
private
def choose_option(scope, label)
# open the widget and click the option
end
def native_select_visibility
:all
end
end
end
ActiveAdminPageObjects::SelectControl.prepend(MyWidget::SelectControl)A theme or plugin ships its own page objects in its own repository, with one entry point. The rule:
- A new component gets a new section in that gem.
- A change to a vanilla component ships as a patch to the base section: a selector override with
register_selectors, or a module prepended to the base class.
# lib/my_plugin/page_objects.rb
require "active_admin_page_objects"
ActiveAdminPageObjects.check_version!(">= 1.0.0.a", "< 2.0.0.a", plugin: "my_plugin")
module MyPlugin
class Widget < ActiveAdminPageObjects::Section
# ...
end
end
ActiveAdminPageObjects::Layout.add_section(:widget, MyPlugin::Widget)Apps load it with require "my_plugin/page_objects".
bundle install
bundle exec rspec
BUNDLE_GEMFILE=gemfiles/site_prism_5.gemfile bundle exec rspec
bundle exec rubocopThe specs drive a Rails 8 dummy app with ActiveAdmin 3.5.2 (spec/dummy) through headless Chrome with Cuprite. The dummy app uses sprockets and dartsass-sprockets, so it needs no Node.
MIT