Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# Changelog

## 1.2.0 (2026-12-02)

### Added

- `Filters` returns a `CheckBoxesFilter` for a check_boxes filter (`filter :tier, as: :check_boxes`): `set`, `check`, `uncheck`, `options`, `checked`, and `have_checked`.
- `Scopes#href(label)` and `#hrefs`.
- `MainMenu#has_submenu?(*labels)` and `#has_no_submenu?`: whether an item is a parent. A parent links to "#", so `href:` cannot tell it apart.
- `HasMany#fieldset(label:)`, `#has_fieldset?(label:)` and `#has_no_fieldset?(label:)` find a fieldset by the label of one of its own fields, ignoring case and formtastic's required marker. A nested has_many's labels do not count. This fits a has_many that labels each record's input with the record's name.
- `have_action_item` and `have_no_action_item` on a page: `has_no_action_item?` passes on a page without the action items container, where `action_items.has_no_item?` raises.
- `Form.object_name "name"` sets the prefix of the field names and ids, for a form named after another object.
- `BatchActions#click(label)` clicks an action and waits for no dialog, for an app that refuses the selection, such as with an error flash.
- `Tabs#body(label)` reads a tab's body by label, which also works under `rack_test`, where `current` is nil.
- `ModalDialog#has_field?` and `#has_no_field?` take the filters of Capybara's `:field` selector, such as `with:`, `type:`, `disabled:` and `placeholder:`.

### Fixed

- `Comments#add` checks for the new comment in the reloaded page. With `Capybara.automatic_reload` off, it raised `ObsoleteNode` on the panel found before the submit.
- `Form::Field#required?` is also true when the label holds `<abbr title="required">` and the wrapper is `optional`.
- The form's field prefix skips a control without a key in brackets, such as a hidden `collection_selection[]` before the fields of a custom batch action form.
- A Symbol field key keeps a leading underscore, as formtastic ids it: `field(:_memo)` finds `#customer__memo_input`. Column, row and filter keys still drop it, as ActiveAdmin's `col-` and `row-` classes do.

## 1.1.0 (2026-12-01)

### Added
Expand Down
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ 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.
ActiveAdmin 3 renders the container in its title bar, so assert on its items, not on the section. A custom page without the title bar has no container: `action_items` raises there. The page's `have_action_item` and `have_no_action_item` treat a missing container as no items:

```ruby
expect(page_object).to have_no_action_item("Edit Customer") # also passes without a title bar
```

A `dropdown_menu` is an item too. `dropdown(label)` returns a `DropdownMenu` (the only one when called without a label):

Expand Down Expand Up @@ -150,6 +154,7 @@ 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")
expect(page_object.main_menu).to have_submenu("Catalog") # a parent; its link is "#"
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"]
Expand Down Expand Up @@ -289,7 +294,7 @@ comments.delete("Called back") # accepts the browser confirmation

### Filters

`filter(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](#declared-labels) 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.
`filter(key)` returns the section typed by the filter input: `StringFilter`, `NumericFilter`, `SelectFilter`, `BooleanFilter`, `DateRangeFilter` or `CheckBoxesFilter`. The key is the one given to `filter :key`; the section wraps `#q_<key>_input`. Filters that [declare their filters](#declared-labels) 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.

```ruby
filters = index.filters
Expand All @@ -298,13 +303,15 @@ 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.filter(:tier).set(%w[Gold Silver]) # check_boxes: ticks these, unticks the rest
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")
expect(filters.filter(:tier)).to have_checked("Gold", "Silver")
```

`DateRangeFilter` types the dates into the two inputs. It does not use the jQuery UI datepicker: it closes the picker through jQuery UI and waits until it is hidden, so the picker never covers the **Filter** button. `set` takes Date objects or ISO strings; `nil` or `""` clears that end.
Expand Down Expand Up @@ -335,6 +342,8 @@ 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 count
index.scopes.href("Active") # => "/admin/customers?scope=active"
index.scopes.hrefs # => {"All" => "/admin/customers?scope=all", "Active" => "..."}
```

### Pagination
Expand Down Expand Up @@ -375,8 +384,12 @@ index.batch_actions.apply(:destroy)
index.batch_actions.apply("Set Status Selected", status: "pending")
expect(index.batch_actions).to have_action("Flag Selected")
dialog = index.batch_actions.open_dialog("Set Status Selected") # unconfirmed: see Modal dialog
index.batch_actions.click("Merge Selected") # waits for nothing
expect(index.flashes).to have_flash(:error, "Select at least two customers to merge")
```

`apply` and `open_dialog` wait for the dialog of an action with `confirm:` or `form:`. When the app may refuse the selection and show an error instead, use `click(label)`: it clicks the action and waits for no dialog.

### Modal dialog

`page.modal_dialog` is the dialog ActiveAdmin opens for batch actions. Use it to drive the dialog yourself, for example to cancel:
Expand All @@ -386,6 +399,7 @@ dialog = index.modal_dialog
dialog.title # => "Are you sure you want to do this?"
dialog.fill("status", with: "pending") # input, select or datepicker, by field name
expect(dialog).to have_field("status")
expect(dialog).to have_field("status", with: "pending", disabled: false) # filters of Capybara's :field
dialog.confirm # or dialog.cancel
expect(index).to have_no_modal_dialog
```
Expand All @@ -403,7 +417,7 @@ form.fill(name: "Acme", category: "Retail", active: false) # in this order
form.submit
```

`field(name)` returns the section typed by the formtastic input class. `fill(value)` sets the field the way its type needs.
`field(name)` returns the section typed by the formtastic input class. `fill(value)` sets the field the way its type needs. A Symbol name stays as it is, so `field(:_memo)` finds `#customer__memo_input`. The field ids and names start with the form's object name, which the gem reads from the first control named like `customer[name]`. When a form names its fields otherwise, set it on the form class: `object_name "batch_action_form_inputs"`.

- `Form::StringField` for `string`, `email`, `url`, `phone`, `password`, `number` and `text`: `fill` types the value. `value`.
- `Form::SelectField` for `select`: `fill` picks the option with that label. `options` (without the blank option) and `selected`. The `<select>` is visible: see [Hidden selects](#hidden-selects).
Expand All @@ -414,7 +428,7 @@ form.submit
- `Form::FileField` for `file`: `fill` takes the path of the file and attaches it. A JavaScript driver needs an absolute path.
- `Form::Field` for any other class: `fill` types 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.
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. `required?` is true when formtastic marks the wrapper `required`, or when the label holds `<abbr title="required">`. `force_fill(text)` sets a text control's value with JavaScript, past its `maxlength`, so a spec reaches the server's own check.

```ruby
form.field(:status).options # => ["active", "pending", "closed"]
Expand Down Expand Up @@ -478,6 +492,8 @@ 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"
orders.fieldset(label: "Kyiv") # the fieldset with a field labelled "Kyiv", without the required "*"
expect(orders).to have_fieldset(label: "Kyiv")
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
Expand All @@ -499,8 +515,11 @@ 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")
expect(show.tabs.body("Orders")).to have_text("Order list") # by label
```

`switch` and `current` need a JavaScript driver, because jQuery UI switches the tabs. Under `rack_test`, every tab body shows: read one with `body(label)`. A JavaScript driver shows only the open tab's body, so `switch` to a tab before you read it there.

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/)`.

## Declared labels
Expand Down
10 changes: 10 additions & 0 deletions lib/active_admin_page_objects/batch_actions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def open_dialog(label)
click_for_dialog(item)
end

# Opens the menu and clicks the action labelled or named +label+, waiting
# for nothing: not for a dialog, nor for a page load. Use it when the app
# may refuse the selection, such as with an error flash instead of the
# action's dialog.
# @return [nil]
def click(label)
open_menu_item(label).click
nil
end

# True when the menu has an action labelled +label+ or named +label+.
def has_action?(label, **options)
eventually(**options) { find_action_item(label) }
Expand Down
4 changes: 3 additions & 1 deletion lib/active_admin_page_objects/comments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ def has_no_comment?(text, **options)
# @raise [Capybara::ExpectationNotMet] when the comment does not show up
def add(text)
find(:active_admin, :comment_input).set(text)
session = root_element.session
find(:active_admin, :comment_submit).click
root_element.assert_selector(:css, sel(:comment_body), text: text)
# The submit reloads the page, so this panel's node goes stale: look in the new page.
session.assert_selector(:css, "#{sel(:comments)} #{sel(:comment_body)}", text: text)
end

# Deletes the comment whose body contains +text+, accepting the browser confirmation.
Expand Down
14 changes: 10 additions & 4 deletions lib/active_admin_page_objects/declarations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ def self.visibility(declaration, visible = nil)
# The declaration of +key+ in +declarations+, or nil when nothing is declared.
# @raise [ArgumentError] when keys are declared and +key+ is not one of them
# @return [Hash, nil]
def self.lookup(declarations, key)
def self.lookup(declarations, key, normalized = ActiveAdminPageObjects.slug(key))
return if declarations.empty?

declarations.fetch(ActiveAdminPageObjects.slug(key)) do
declarations.fetch(normalized) do
raise ArgumentError, "#{key.inspect} is not declared; declared keys: #{declarations.keys.join(', ')}"
end
end
Expand Down Expand Up @@ -78,6 +78,12 @@ module ClassMethods
# @return [Hash{String => Hash}] name => `{ label: }`, with `type:` for
# filters, fields and has_many blocks, `kind:` for fields and has_many
# blocks, and `visible:` when the declaration gives it
# The key a declared +name+ is stored under, as the page writes it.
# @return [String]
def declaration_key(name)
ActiveAdminPageObjects.slug(name)
end

def declarations
inherited = superclass.respond_to?(:declarations) ? superclass.declarations : {}
inherited.merge(own_declarations).freeze
Expand All @@ -87,7 +93,7 @@ def declarations

def declare(name, label, visible: nil, **options)
options[:visible] = visible unless visible.nil?
own_declarations[ActiveAdminPageObjects.slug(name)] = { label: label.to_s, **options }.freeze
own_declarations[declaration_key(name)] = { label: label.to_s, **options }.freeze
end

# Declares +name+ with its section class, for the class method +macro+.
Expand Down Expand Up @@ -156,7 +162,7 @@ def declarations_in_scope(only, except)
def declared_names(names)
Array(names).map do |name|
declaration_for(name)
slug(name)
declaration_key(name)
end
end

Expand Down
7 changes: 6 additions & 1 deletion lib/active_admin_page_objects/declarations/lookup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ def declarations

# @raise [ArgumentError] when names are declared and +key+ is not one of them
def declaration_for(key)
Declarations.lookup(declarations, key)
Declarations.lookup(declarations, key, declaration_key(key))
end

# The key +key+ is declared under, as the declaring class normalizes it.
def declaration_key(key)
declaring_class.respond_to?(:declaration_key) ? declaring_class.declaration_key(key) : ActiveAdminPageObjects.slug(key)
end

# The `visible:` option for the declared or undeclared element +key+.
Expand Down
15 changes: 13 additions & 2 deletions lib/active_admin_page_objects/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ def self.included(base)
end

module ClassMethods
# A field keeps a Symbol's leading underscore, as formtastic ids it.
def declaration_key(name)
ActiveAdminPageObjects.field_slug(name)
end

# Declares the field +name+ with its +label+ and its section class
# +type+. +name+ is the formtastic attribute. +visible+ is the Capybara
# option the field is found with, e.g. `:all` for a field that may be hidden.
Expand Down Expand Up @@ -124,16 +129,22 @@ def detectable_classes
# The `name` of the first namespaced control, which the id prefix of the
# wrappers is built from. That control may be hidden: a hidden input, or
# the `<select>` of a JavaScript select widget.
# The first name with a key in brackets, such as `customer[name]`. A
# `collection_selection[]` before the fields has none.
def first_control_name
find("input[name*='['], select[name*='['], textarea[name*='[']", match: :first, visible: :all)[:name]
root_element.synchronize do
controls = all("input[name*='['], select[name*='['], textarea[name*='[']", visible: :all, wait: false)
controls.map { |control| control[:name] }.find { |name| name.match?(/\A[^\[]+\[[^\]]+\]/) } ||
raise(Capybara::ElementNotFound, "no named control in the form")
end
end

# The attribute of the field +name+, checked against the declarations when fields are declared.
def field_key(name)
declaration = declaration_for(name)
raise ArgumentError, "#{name.inspect} is declared as a has_many, not as a field" if declaration&.fetch(:kind) == :has_many

slug(name)
field_slug(name)
end

# Checks the name before #field_prefix queries the page.
Expand Down
4 changes: 3 additions & 1 deletion lib/active_admin_page_objects/filters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ def clear
"numeric" => :NumericFilter,
"select" => :SelectFilter,
"boolean" => :BooleanFilter,
"date_range" => :DateRangeFilter
"date_range" => :DateRangeFilter,
"check_boxes" => :CheckBoxesFilter
}.freeze
private_constant :FILTER_CLASSES

Expand Down Expand Up @@ -89,3 +90,4 @@ def page_element_keys(**visibility)
require_relative "filters/select_filter"
require_relative "filters/boolean_filter"
require_relative "filters/date_range_filter"
require_relative "filters/check_boxes_filter"
63 changes: 63 additions & 0 deletions lib/active_admin_page_objects/filters/check_boxes_filter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# frozen_string_literal: true

module ActiveAdminPageObjects
# A check_boxes filter (`filter :tier, as: :check_boxes`): one checkbox per
# choice, found by its label.
class CheckBoxesFilter < Filter
# Ticks the checkboxes labelled +labels+ and unticks the others.
def set(labels)
labels = Array(labels).map(&:to_s)
uncheck(*(checked - labels))
check(*labels)
end

# Ticks the checkboxes labelled +labels+.
def check(*labels)
labels.each { |label| choice(label).set(true) }
end

# Unticks the checkboxes labelled +labels+.
def uncheck(*labels)
labels.each { |label| choice(label).set(false) }
end

# The choice labels, in page order.
# @return [Array<String>]
def options
choices.map(&:first)
end

# The labels of the ticked checkboxes.
# @return [Array<String>]
def checked
choices.select { |_label, input| input.checked? }.map(&:first)
end

# True when exactly +labels+ are ticked, in any order. No labels: none ticked.
def has_checked?(*labels, **options)
eventually(**options) { checked_labels_match?(labels) }
end

# Waits until the ticked checkboxes are no longer exactly +labels+.
def has_no_checked?(*labels, **options)
eventually(**options) { !checked_labels_match?(labels) }
end

private

def choices
all(:active_admin, :filter_choice, wait: false).map do |label|
[label.text(:all).strip, label.find("input", visible: :all)]
end
end

def choice(label)
choices.find { |text, _input| same_text?(text, label) }&.last ||
raise(Capybara::ElementNotFound, "no choice #{label.inspect} in #{options.inspect}")
end

def checked_labels_match?(labels)
checked.map { |label| normalize_text(label) }.sort == labels.map { |label| normalize_text(label) }.sort
end
end
end
Loading
Loading