From 60e84a9672bf632a9f694ba8d05898d9a4cdc0a6 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Thu, 26 Nov 2026 15:59:29 +0200 Subject: [PATCH 1/7] Ignore case in cell and row text matchers Chrome reports text after CSS text-transform, so a status tag the theme uppercases failed exact_text: "verified". Co-Authored-By: Clanker --- CHANGELOG.md | 1 + README.md | 4 +++- .../attributes_table.rb | 7 +++--- lib/active_admin_page_objects/table.rb | 11 +++++---- lib/active_admin_page_objects/text.rb | 23 +++++++++++++++++++ .../attributes_table_spec.rb | 4 ++++ spec/active_admin_page_objects/table_spec.rb | 6 +++++ spec/active_admin_page_objects/text_spec.rb | 9 ++++++++ 8 files changed, 56 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edd3321..4028fb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Added +- `Table::Row#has_cell?`, `Table#has_row?`, `AttributesTable#has_row?` and their `has_no_` forms ignore case for a String `text:` or `exact_text:`. Chrome reports text as CSS shows it, so a theme that uppercases a value no longer breaks the match. - `StringFilter` and `NumericFilter` drive a filter whose key holds its predicate, such as `filter :uuid_eq`: ActiveAdmin renders a bare input without a predicate select. - `Form::Field#required?`, `#input` (the field's first control) and `#force_fill(text)`, which sets a text control's value with JavaScript past its `maxlength`. - `Table#row_with(key, text)`, `#has_row_with?` and `#has_no_row_with?` find a row by a cell's text, for tables without record ids. diff --git a/README.md b/README.md index 3befe46..ae00e73 100644 --- a/README.md +++ b/README.md @@ -149,13 +149,15 @@ table.row_with(:server, "10.0.0.1:7080") # by a cell's whole text; a Regexp matc expect(table).to have_row_with(:status, "Failed") ``` +`have_cell`, `have_row` and their `have_no_` forms ignore case when `text:` or `exact_text:` is a String, so a value the theme uppercases in CSS still matches. A Regexp is passed to Capybara unchanged. + `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`. The section defaults to `table.data-table`. Pass a locator for another table, such as a `table_for` inside a panel: `section :orders, ActiveAdminPageObjects::Table, "#orders_panel table"`. ### Attributes table -Rows are keyed by the `row :foo` symbol, or by the label parameterized with `_`. +Rows are keyed by the `row :foo` symbol, or by the label parameterized with `_`. As in the index table, a String `text:` or `exact_text:` ignores case. ```ruby table = show.attributes_table diff --git a/lib/active_admin_page_objects/attributes_table.rb b/lib/active_admin_page_objects/attributes_table.rb index 8a665ab..26ec518 100644 --- a/lib/active_admin_page_objects/attributes_table.rb +++ b/lib/active_admin_page_objects/attributes_table.rb @@ -22,14 +22,15 @@ def row(key, label, visible: nil) end end - # True when row +key+ has a value cell matching the Capybara options. + # True when row +key+ has a value cell matching the Capybara options. A + # String `text:` or `exact_text:` ignores case. def has_row?(key, **options) - has_css?(cell_selector(key), **visibility_of(key), **options) + has_css?(cell_selector(key), **visibility_of(key), **case_insensitive_text(options)) end # Waits until row +key+ has no value cell matching the Capybara options. def has_no_row?(key, **options) - has_no_css?(cell_selector(key), **visibility_of(key), **options) + has_no_css?(cell_selector(key), **visibility_of(key), **case_insensitive_text(options)) end # The `` of row +key+. A hidden row is found with `visible: :all`. diff --git a/lib/active_admin_page_objects/table.rb b/lib/active_admin_page_objects/table.rb index a6d9d66..495d12d 100644 --- a/lib/active_admin_page_objects/table.rb +++ b/lib/active_admin_page_objects/table.rb @@ -46,14 +46,15 @@ def cell(key, visible: nil) find(:css, cell_selector(key), **visibility_of(key, visible)) end - # True when column +key+ has a cell matching the Capybara options. + # True when column +key+ has a cell matching the Capybara options. A + # String `text:` or `exact_text:` ignores case. def has_cell?(key, **options) - has_css?(cell_selector(key), **visibility_of(key), **options) + has_css?(cell_selector(key), **visibility_of(key), **case_insensitive_text(options)) end # Waits until column +key+ has no cell matching the Capybara options. def has_no_cell?(key, **options) - has_no_css?(cell_selector(key), **visibility_of(key), **options) + has_no_css?(cell_selector(key), **visibility_of(key), **case_insensitive_text(options)) end # Ticks the row's batch-action checkbox. @@ -86,13 +87,13 @@ def row(record_id) # True when the body has the row of the record with +record_id+. # @raise [ArgumentError] when +record_id+ is not an Integer or a non-empty String def has_row?(record_id, **options) - has_css?(row_selector(record_id), **options) + has_css?(row_selector(record_id), **case_insensitive_text(options)) end # Waits until the body has no row of the record with +record_id+. # @raise [ArgumentError] when +record_id+ is not an Integer or a non-empty String def has_no_row?(record_id, **options) - has_no_css?(row_selector(record_id), **options) + has_no_css?(row_selector(record_id), **case_insensitive_text(options)) end # The non-empty header texts, as the driver reports them (Chrome reports diff --git a/lib/active_admin_page_objects/text.rb b/lib/active_admin_page_objects/text.rb index ad41412..29cca32 100644 --- a/lib/active_admin_page_objects/text.rb +++ b/lib/active_admin_page_objects/text.rb @@ -26,6 +26,29 @@ def text_match?(actual, expected) expected.is_a?(Regexp) ? expected.match?(squish(actual)) : same_text?(actual, expected) end + # Capybara options with a String `text:` or `exact_text:` turned into a + # case-insensitive Regexp in `text:`. Chrome reports CSS-transformed text, + # so a tag uppercased by the theme still matches "verified". + # @return [Hash] + def case_insensitive_text(options) + text = options[:text] + exact = options[:exact_text] + if exact.is_a?(String) && text.nil? + options.except(:exact_text).merge(text: text_pattern(exact, exact: true)) + elsif text.is_a?(String) + options.except(:exact_text).merge(text: text_pattern(text, exact: exact == true)) + else + options + end + end + + # A Regexp matching +text+ with any whitespace between its words, ignoring case. + # @return [Regexp] + def text_pattern(text, exact: false) + words = text.to_s.split.map { |word| Regexp.escape(word) }.join("\\s+") + Regexp.new(exact ? "\\A\\s*#{words}\\s*\\z" : words, Regexp::IGNORECASE) + end + # A date as the date inputs take it: "2026-01-31" for a Date or a Time, # and the text of anything else. # @return [String] diff --git a/spec/active_admin_page_objects/attributes_table_spec.rb b/spec/active_admin_page_objects/attributes_table_spec.rb index f6d0873..0143d32 100644 --- a/spec/active_admin_page_objects/attributes_table_spec.rb +++ b/spec/active_admin_page_objects/attributes_table_spec.rb @@ -16,6 +16,10 @@ def declared_table(&) expect(show.attributes_table).to have_row(:name, exact_text: "Acme") expect(show.attributes_table).to have_row("Signed up") expect(show.attributes_table).to have_no_row(:name, exact_text: "Other") + expect(show.attributes_table).to have_row(:name, exact_text: "ACME") + expect(show.attributes_table).to have_row(:category, text: "wholesale") + expect(show.attributes_table).to have_no_row(:name, exact_text: "acm") + expect(show.attributes_table.has_no_row?(:name, exact_text: "acme", wait: 0)).to be(false) end it "reads a row and its value" do diff --git a/spec/active_admin_page_objects/table_spec.rb b/spec/active_admin_page_objects/table_spec.rb index 38c8619..3a914e4 100644 --- a/spec/active_admin_page_objects/table_spec.rb +++ b/spec/active_admin_page_objects/table_spec.rb @@ -109,6 +109,7 @@ def declared_table(&) expect(table).to have_no_row(customers.last.id + 1) expect(table).to have_row(customers.first.id, text: customers.first.name) expect(table).to have_no_row(customers.first.id, text: "No such customer") + expect(table).to have_row(customers.first.id, text: customers.first.name.upcase) expect(table.has_no_row?(customers.first.id, wait: 0)).to be(false) expect(table.has_row?(customers.last.id + 1, wait: 0)).to be(false) end @@ -130,6 +131,11 @@ def declared_table(&) expect(row).to have_cell(:name, exact_text: customer.name) expect(row).to have_cell("CATEGORY", exact_text: "Retail") expect(row).to have_no_cell(:name, exact_text: "Nobody") + expect(row).to have_cell(:category, exact_text: "RETAIL") + expect(row).to have_cell(:category, text: "retail") + expect(row).to have_cell(:category, text: "RET", exact_text: false) + expect(row).to have_no_cell(:category, exact_text: "RET") + expect(row.has_no_cell?(:category, exact_text: "retail", wait: 0)).to be(false) expect(row.cell(:email)).to have_text(customer.email) end diff --git a/spec/active_admin_page_objects/text_spec.rb b/spec/active_admin_page_objects/text_spec.rb index 9719c86..05beed2 100644 --- a/spec/active_admin_page_objects/text_spec.rb +++ b/spec/active_admin_page_objects/text_spec.rb @@ -14,6 +14,15 @@ expect(ActiveAdminPageObjects.same_text?("Created", "Created at")).to be(false) end + it "turns a String text option into a case-insensitive Regexp" do + expect(ActiveAdminPageObjects.case_insensitive_text(exact_text: "a.b c", visible: :all)) + .to eq(text: /\A\s*a\.b\s+c\s*\z/i, visible: :all) + expect(ActiveAdminPageObjects.case_insensitive_text(text: "No", exact_text: true)).to eq(text: /\A\s*No\s*\z/i) + expect(ActiveAdminPageObjects.case_insensitive_text(text: "No")).to eq(text: /No/i) + expect(ActiveAdminPageObjects.case_insensitive_text(text: /No/)).to eq(text: /No/) + expect(ActiveAdminPageObjects.case_insensitive_text(count: 1)).to eq(count: 1) + end + it "squishes whitespace and keeps the case" do expect(ActiveAdminPageObjects.squish(" External\n ID ")).to eq("External ID") end From 162118bebc5df50bacc567a3a8e90e4008ec60b7 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 27 Nov 2026 14:44:42 +0200 Subject: [PATCH 2/7] Point repo links at the activeadmin-plugins org Co-Authored-By: Clanker --- README.md | 2 +- active_admin_page_objects.gemspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ae00e73..a46ef41 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Until the first release, install it from git: ```ruby # Gemfile group :test do - gem "active_admin_page_objects", github: "senid231/active_admin_page_objects" + gem "active_admin_page_objects", github: "activeadmin-plugins/active_admin_page_objects" end ``` diff --git a/active_admin_page_objects.gemspec b/active_admin_page_objects.gemspec index cf6dc0f..efc953c 100644 --- a/active_admin_page_objects.gemspec +++ b/active_admin_page_objects.gemspec @@ -12,7 +12,7 @@ Gem::Specification.new do |spec| spec.description = "SitePrism pages and sections for vanilla ActiveAdmin 4's layout, index tables, filters, " \ "scopes, batch actions, show pages and forms, so system specs call semantic methods " \ "instead of CSS selectors." - spec.homepage = "https://github.com/senid231/active_admin_page_objects" + spec.homepage = "https://github.com/activeadmin-plugins/active_admin_page_objects" spec.license = "MIT" spec.required_ruby_version = ">= 3.3" From e174bd45a529e01a5722bf9b5f1cc5a68d932742 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 27 Nov 2026 17:12:40 +0200 Subject: [PATCH 3/7] Find the actions cell and let themes add flash types ActiveAdmin 4 writes no data-column on the actions cell, so row.cell(:actions) never matched. Flashes#flash_types lets a theme accept the types it renders. Co-Authored-By: Clanker --- CHANGELOG.md | 3 +++ lib/active_admin_page_objects/flashes.rb | 9 +++++++-- lib/active_admin_page_objects/selectors.rb | 1 + lib/active_admin_page_objects/table.rb | 3 ++- lib/active_admin_page_objects/table/rows_by_cell.rb | 3 ++- spec/active_admin_page_objects/table_spec.rb | 2 ++ 6 files changed, 17 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4028fb1..33cc333 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Added +- `Table::Row#cell(:actions)`, `has_cell?(:actions)` and `Table#row_with(:actions, ...)` find the actions cell. ActiveAdmin 4 writes no `data-column` on it, so these lookups used to fail. +- `Flashes#flash_types`, a private method that a theme overrides to add the flash types it renders. + - `Table::Row#has_cell?`, `Table#has_row?`, `AttributesTable#has_row?` and their `has_no_` forms ignore case for a String `text:` or `exact_text:`. Chrome reports text as CSS shows it, so a theme that uppercases a value no longer breaks the match. - `StringFilter` and `NumericFilter` drive a filter whose key holds its predicate, such as `filter :uuid_eq`: ActiveAdmin renders a bare input without a predicate select. - `Form::Field#required?`, `#input` (the field's first control) and `#force_fill(text)`, which sets a text control's value with JavaScript past its `maxlength`. diff --git a/lib/active_admin_page_objects/flashes.rb b/lib/active_admin_page_objects/flashes.rb index 451adc0..3e7d5dc 100644 --- a/lib/active_admin_page_objects/flashes.rb +++ b/lib/active_admin_page_objects/flashes.rb @@ -29,11 +29,16 @@ def messages(type = nil) private def flash_selector(type) - unless type.respond_to?(:to_sym) && TYPES.include?(type.to_sym) - raise ArgumentError, "flash type must be one of #{TYPES.inspect}, got #{type.inspect}" + unless type.respond_to?(:to_sym) && flash_types.include?(type.to_sym) + raise ArgumentError, "flash type must be one of #{flash_types.inspect}, got #{type.inspect}" end sel(:"flash_#{type}") end + + # The types this layout renders. A theme that renders more overrides it. + def flash_types + TYPES + end end end diff --git a/lib/active_admin_page_objects/selectors.rb b/lib/active_admin_page_objects/selectors.rb index 275dd2c..ab4c9dd 100644 --- a/lib/active_admin_page_objects/selectors.rb +++ b/lib/active_admin_page_objects/selectors.rb @@ -39,6 +39,7 @@ module Selectors table_row_checkbox: "input.batch-actions-resource-selection", # The cells of the actions column at a 1-based column position. table_actions_cell: "tbody > tr > td:nth-child(%s) .data-table-resource-actions", + table_row_actions_cell: "td:has(.data-table-resource-actions)", blank_slate: ".main-content-container .border-dashed", attributes_table: ".attributes-table", diff --git a/lib/active_admin_page_objects/table.rb b/lib/active_admin_page_objects/table.rb index 495d12d..e07482d 100644 --- a/lib/active_admin_page_objects/table.rb +++ b/lib/active_admin_page_objects/table.rb @@ -71,7 +71,8 @@ def declaring_class def cell_selector(key) declaration_for(key) - sel(:table_cell, slug(key)) + column = slug(key) + column == ACTIONS_COLUMN ? sel(:table_row_actions_cell) : sel(:table_cell, column) end end diff --git a/lib/active_admin_page_objects/table/rows_by_cell.rb b/lib/active_admin_page_objects/table/rows_by_cell.rb index cc078d3..280974d 100644 --- a/lib/active_admin_page_objects/table/rows_by_cell.rb +++ b/lib/active_admin_page_objects/table/rows_by_cell.rb @@ -32,7 +32,8 @@ def eventually_row(key, text, **options) def find_row_with(key, text) declaration_for(key) - cell_css = sel(:table_cell, slug(key)) + column = slug(key) + cell_css = column == ACTIONS_COLUMN ? sel(:table_row_actions_cell) : sel(:table_cell, column) rows.find do |row| cell = row.first(:css, cell_css, minimum: 0, wait: false, **visibility_of(key)) cell && text_match?(cell.text, text) diff --git a/spec/active_admin_page_objects/table_spec.rb b/spec/active_admin_page_objects/table_spec.rb index 3a914e4..a2040b8 100644 --- a/spec/active_admin_page_objects/table_spec.rb +++ b/spec/active_admin_page_objects/table_spec.rb @@ -137,6 +137,8 @@ def declared_table(&) expect(row).to have_no_cell(:category, exact_text: "RET") expect(row.has_no_cell?(:category, exact_text: "retail", wait: 0)).to be(false) expect(row.cell(:email)).to have_text(customer.email) + expect(row.cell(:actions)).to have_link("Delete") + expect(row).to have_cell(:actions, text: "edit") end it "keeps rows in table order" do From 8ec1677d4118559af117421fbf6576cdd5e33721 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Fri, 27 Nov 2026 18:43:02 +0200 Subject: [PATCH 4/7] Add comments, has_many, status tag and sorting sections Ports the 1.x comments, has_many and status tag sections to ActiveAdmin 4 markup and adds table sorting. A panel nested in another is now found by its own title instead of matching the outer panel too. Co-Authored-By: Clanker --- CHANGELOG.md | 5 + README.md | 69 ++++ lib/active_admin_page_objects.rb | 8 +- lib/active_admin_page_objects/comments.rb | 64 ++++ lib/active_admin_page_objects/fields.rb | 34 +- lib/active_admin_page_objects/form.rb | 56 +++- lib/active_admin_page_objects/has_many.rb | 104 ++++++ lib/active_admin_page_objects/panel.rb | 7 +- lib/active_admin_page_objects/selectors.rb | 26 +- lib/active_admin_page_objects/status_tag.rb | 141 ++++++++ lib/active_admin_page_objects/table.rb | 103 ++++++ .../attributes_table_spec.rb | 2 +- .../comments_spec.rb | 82 +++++ .../has_many_spec.rb | 305 ++++++++++++++++++ spec/active_admin_page_objects/panel_spec.rb | 8 + .../status_tag_spec.rb | 132 ++++++++ spec/active_admin_page_objects/table_spec.rb | 69 ++++ spec/dummy/app/admin/customers.rb | 10 +- spec/dummy/app/admin/dashboard.rb | 5 + spec/dummy/app/admin/documents.rb | 4 +- spec/dummy/app/admin/orders.rb | 21 ++ .../app/controllers/application_controller.rb | 6 +- spec/dummy/app/models/admin_user.rb | 6 + spec/dummy/app/models/line_item.rb | 12 + spec/dummy/app/models/order.rb | 3 + spec/dummy/config/schema.rb | 19 ++ spec/spec_helper.rb | 2 +- spec/support/pages.rb | 16 + 28 files changed, 1289 insertions(+), 30 deletions(-) create mode 100644 lib/active_admin_page_objects/comments.rb create mode 100644 lib/active_admin_page_objects/has_many.rb create mode 100644 lib/active_admin_page_objects/status_tag.rb create mode 100644 spec/active_admin_page_objects/comments_spec.rb create mode 100644 spec/active_admin_page_objects/has_many_spec.rb create mode 100644 spec/active_admin_page_objects/status_tag_spec.rb create mode 100644 spec/dummy/app/models/admin_user.rb create mode 100644 spec/dummy/app/models/line_item.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 33cc333..c0b0075 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ - `Table::Row#cell(:actions)`, `has_cell?(:actions)` and `Table#row_with(:actions, ...)` find the actions cell. ActiveAdmin 4 writes no `data-column` on it, so these lookups used to fail. - `Flashes#flash_types`, a private method that a theme overrides to add the flash types it renders. +- `Comments` section for resource comments: `count`, `bodies`, `authors`, `has_comment?`, `add` and `delete`. The `form` selector leaves the comment form out. +- has_many support: `Form.has_many`, `Form#has_many` and the `HasMany` section with fieldsets, `add`, `remove` and `marked_for_destroy?`. `have_exact_fields` counts a has_many block as one declared element, so a form with an undeclared has_many block reports it as unexpected. +- Status tags: `Table::Row` and `AttributesTable` get `status_tag(key)`, `status_tags(key)`, `has_status_tag?(key, label = nil, status:)` and `has_no_status_tag?`. `type:` is an alias of `status:`. +- Sorting: `Table#sort_by(key, direction = nil)`, `#sort_direction`, `#has_sort?` (alias `sorted_by?`), `#has_no_sort?`, `#has_sortable_column?` and `#has_no_sortable_column?`. +- A panel nested in another panel is found by its own title; before, the outer panel matched too and Capybara raised `Ambiguous`. - `Table::Row#has_cell?`, `Table#has_row?`, `AttributesTable#has_row?` and their `has_no_` forms ignore case for a String `text:` or `exact_text:`. Chrome reports text as CSS shows it, so a theme that uppercases a value no longer breaks the match. - `StringFilter` and `NumericFilter` drive a filter whose key holds its predicate, such as `filter :uuid_eq`: ActiveAdmin renders a bare input without a predicate select. diff --git a/README.md b/README.md index a46ef41..d39ce32 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,30 @@ expect(table).to have_row_with(:status, "Failed") The section defaults to `table.data-table`. Pass a locator for another table, such as a `table_for` inside a panel: `section :orders, ActiveAdminPageObjects::Table, "#orders_panel table"`. +Sortable columns: ActiveAdmin 4 marks a sortable header with `data-sortable` and the sorted one with `data-sort-direction`. + +```ruby +expect(table).to have_sortable_column(:name) +table.sort_by(:name) # clicks the header; an unsorted column sorts :desc first +table.sort_by(:name, :asc) # clicks until the column shows :asc +expect(table).to have_sort(:name, :asc) # also sorted_by?(:name, :asc) +expect(table).to have_no_sort(:email) +table.sort_direction(:id) # => :desc, without waiting +``` + +#### Status tags + +A row of an index table or an attributes table finds the `status_tag` in a cell. `status:` compares the tag's `data-status`, and `type:` is an alias of it; passing both raises `ArgumentError`. A String label is the whole text, ignoring case; a Regexp matches part of it. + +```ruby +row = index.table.row(customer.id) +expect(row).to have_status_tag(:status, "Pending", status: :pending) +expect(row).to have_no_status_tag(:status, status: :failed) +row.status_tag(:status).status # => "pending" +row.status_tags(:flags).map(&:label) +expect(show.attributes_table).to have_status_tag(:active, status: true) # true is "yes", false is "no" +``` + ### Attributes table Rows are keyed by the `row :foo` symbol, or by the label parameterized with `_`. As in the index table, a String `text:` or `exact_text:` ignores case. @@ -192,6 +216,25 @@ section :routes, ActiveAdminPageObjects::Panel, :active_admin_panel, /\APossible show.panel(/\APossible Routes/).title # => "Possible Routes (2)" ``` +A panel nested in another panel's body is found by its own title, and the outer panel's `title` and `body` are its own. + +### Comments + +Declare the comments of a show page; ActiveAdmin renders them when the resource has `config.comments = true`. A custom `show` block must call `active_admin_comments_for(resource)`. + +```ruby +section :comments, ActiveAdminPageObjects::Comments + +show.comments.count # from the "All Comments (N)" title +show.comments.bodies +show.comments.authors +expect(show.comments).to have_comment("Called the customer") +show.comments.add("Called the customer") +show.comments.delete("Called the customer") # accepts the browser confirm +``` + +The base `form` selector leaves the comment form out. + ### 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__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. @@ -328,6 +371,30 @@ form.field(:code).disabled? # => true, without waiting - `have_no_disabled_field` and `have_no_enabled_field` also pass when the form has no such field. - The matchers wait, and take `visible:` like `field`. +#### has_many + +Declare a has_many block with its heading and the fields of one fieldset, then reach it with `form.has_many`: + +```ruby +section :form, ActiveAdminPageObjects::Form do + field :reference, "Reference", ActiveAdminPageObjects::Form::StringField + has_many :line_items, "Line Items" do + field :sku, "Sku", ActiveAdminPageObjects::Form::StringField + end +end + +items = form_page.form.has_many(:line_items) +items.heading # => "Line Items" +items.count # number of fieldsets +items.add.fill(sku: "SKU-1") # clicks the add link +items.fieldset(0).field(:sku).value +items.remove(0) # the remove link of a new fieldset, the delete checkbox of a saved one +items.fieldset(0).marked_for_destroy? +expect(items).to have_fieldsets(count: 2) +``` + +A fieldset has the form's field API. `have_exact_fields` counts a has_many block once, as its declared element, and skips its inner inputs; ask each fieldset for its own. The destroy checkbox is not a field, and asking for a has_many name as a field raises `ArgumentError`. + #### Form errors ```ruby @@ -657,6 +724,8 @@ These need a JavaScript driver such as Cuprite or Selenium: - `BatchActions#apply`: ActiveAdmin's JavaScript opens the menu and submits the form. - `StringFilter#fill_in` and `NumericFilter#fill_in` with 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. +- `HasMany#add` and `#remove` on a new fieldset: ActiveAdmin's JavaScript adds and removes the fieldset. +- `Comments#delete`: it accepts the browser confirm. Everything else works with `rack_test` too, including `MainMenu#go` and `MainMenu#click`, filters with the current predicate, plain selects, date ranges, scopes, pagination and forms. diff --git a/lib/active_admin_page_objects.rb b/lib/active_admin_page_objects.rb index 2b5a24b..95f4ecb 100644 --- a/lib/active_admin_page_objects.rb +++ b/lib/active_admin_page_objects.rb @@ -37,8 +37,9 @@ def self.check_version!(*requirements, plugin:) locator_filter do |node, title| next true if title.nil? - titles = node.all(:css, ActiveAdminPageObjects.selector(:panel_title), visible: :all, wait: false) - titles.any? { |el| ActiveAdminPageObjects.text_match?(el.text(:all), title) } + # The panel's own title comes before the titles of panels nested in its body. + own = node.first(:css, ActiveAdminPageObjects.selector(:panel_title), visible: :all, minimum: 0, wait: false) + own && ActiveAdminPageObjects.text_match?(own.text(:all), title) end end @@ -54,7 +55,9 @@ def self.check_version!(*requirements, plugin:) require_relative "active_admin_page_objects/table/rows_by_cell" require_relative "active_admin_page_objects/table" require_relative "active_admin_page_objects/attributes_table" +require_relative "active_admin_page_objects/status_tag" require_relative "active_admin_page_objects/panel" +require_relative "active_admin_page_objects/comments" require_relative "active_admin_page_objects/filters" require_relative "active_admin_page_objects/filters_footer" require_relative "active_admin_page_objects/scopes" @@ -63,4 +66,5 @@ def self.check_version!(*requirements, plugin:) require_relative "active_admin_page_objects/batch_actions" require_relative "active_admin_page_objects/fields" require_relative "active_admin_page_objects/form" +require_relative "active_admin_page_objects/has_many" require_relative "active_admin_page_objects/tabs" diff --git a/lib/active_admin_page_objects/comments.rb b/lib/active_admin_page_objects/comments.rb new file mode 100644 index 0000000..8449f38 --- /dev/null +++ b/lib/active_admin_page_objects/comments.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +module ActiveAdminPageObjects + # The comments of a show page. Declare it on the page; the page must render + # them, which the default show page does and a custom `show` block does not + # until it calls `active_admin_comments_for(resource)`: + # + # section :comments, ActiveAdminPageObjects::Comments + class Comments < Section + selector_key :comments + + # The number in the "All Comments (N)" title. + # @return [Integer] + def count + find(:active_admin, :comments_title).text[/\((\d+)\)/, 1].to_i + end + + # The comment body texts, in page order. + # @return [Array] + def bodies + all(:active_admin, :comment_body, wait: false).map { |el| el.text.strip } + end + + # The comment author texts, in page order. + # @return [Array] + def authors + all(:active_admin, :comment_author, wait: false).map { |el| el.text.strip } + end + + # True when a comment body contains +text+. Pass `exact_text:` for a full match. + def has_comment?(text, **options) + has_css?(sel(:comment_body), text: text, **options) + end + + # Waits until no comment body contains +text+. + def has_no_comment?(text, **options) + has_no_css?(sel(:comment_body), text: text, **options) + end + + # Types +text+ into the comment form and submits it. + # @raise [Capybara::ExpectationNotMet] when the comment does not show up + def add(text) + find(:active_admin, :comment_input).set(text) + find(:active_admin, :comment_submit).click + root_element.assert_selector(:css, sel(:comment_body), text: text) + end + + # Deletes the comment whose body contains +text+, accepting the browser confirmation. + def delete(text) + link = comment_for(text).find(:active_admin, :comment_delete) + accept_confirm { link.click } + end + + private + + def comment_for(text) + root_element.synchronize do + all(:active_admin, :comment, wait: false).find do |comment| + comment.has_css?(sel(:comment_body), text: text, wait: false) + end || raise(Capybara::ElementNotFound, "no comment containing #{text.inspect}") + end + end + end +end diff --git a/lib/active_admin_page_objects/fields.rb b/lib/active_admin_page_objects/fields.rb index 55a6f2a..969b116 100644 --- a/lib/active_admin_page_objects/fields.rb +++ b/lib/active_admin_page_objects/fields.rb @@ -3,9 +3,9 @@ require_relative "fields/states" module ActiveAdminPageObjects - # The fields of a formtastic form. Form includes it. A field is named by its - # attribute, as in `f.input :name`, or by its declared name when the section - # declares fields: + # The fields of a formtastic form, or of one has_many fieldset. Form and + # HasMany::Fieldset include it. A field is named by its attribute, as in + # `f.input :name`, or by its declared name when the section declares fields: # # section :form, ActiveAdminPageObjects::Form do # field :email, "Email", ActiveAdminPageObjects::Form::StringField @@ -71,20 +71,21 @@ def has_no_field_error?(name, text = nil, **options) has_no_css?(field_error_selector(name), **visibility_of(name), **given(text: text), **options) end - # True when any field shows an inline error. + # True when any field shows an inline error, has_many fieldsets included. def has_field_errors?(**options) has_css?(sel(:form_inline_error), **options) end - # Waits until no field shows an inline error. + # Waits until no field shows an inline error, has_many fieldsets included. def has_no_field_errors?(**options) has_no_css?(sel(:form_inline_error), **options) end # True when the inline errors are exactly +errors+: field name => message, - # or an array of messages. No other field shows an error. Every keyword is - # a field name, so there is no `visible:` option: a hidden field counts - # only when it is declared with `visible:`. + # or an array of messages. No other field shows an error. The fields of + # has_many fieldsets are left out: ask each fieldset. Every keyword is a + # field name, so there is no `visible:` option: a hidden field counts only + # when it is declared with `visible:`. def has_exact_field_errors?(**errors) exact_field_errors?(true, errors) end @@ -129,7 +130,9 @@ def first_control_name # The attribute of the field +name+, checked against the declarations when fields are declared. def field_key(name) - declaration_for(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) end @@ -143,10 +146,17 @@ def field_error_selector(name) "#{field_selector(name)} #{sel(:form_inline_error)}" end - # The attributes of the input wrappers on the page. + # The attributes of the input wrappers on the page. The wrappers inside a + # has_many block belong to its fieldsets and are left out: the hidden ones + # too, so that query takes every wrapper. def field_keys(prefix, **visibility) - wrappers = all(:active_admin, :form_input_wrapper, wait: false, **visibility) - wrappers.filter_map { |wrapper| wrapper[:id].to_s[/\A#{Regexp.escape(prefix)}_(.+)_input\z/, 1] } + containers = all(:active_admin, :has_many_container, visible: :all, wait: false) + nested = containers.flat_map { |node| wrapper_ids(node, visible: :all) } + (wrapper_ids(self, **visibility) - nested).filter_map { |id| id[/\A#{Regexp.escape(prefix)}_(.+)_input\z/, 1] } + end + + def wrapper_ids(scope, **visibility) + scope.all(:active_admin, :form_input_wrapper, wait: false, **visibility).map { |wrapper| wrapper[:id].to_s } end # Attribute => sorted inline error texts, for the fields that show an error. diff --git a/lib/active_admin_page_objects/form.rb b/lib/active_admin_page_objects/form.rb index faa34a8..8935c64 100644 --- a/lib/active_admin_page_objects/form.rb +++ b/lib/active_admin_page_objects/form.rb @@ -3,11 +3,15 @@ module ActiveAdminPageObjects # A formtastic resource form (new and edit pages). Fields are named by the # attribute: `field(:email).fill("acme@example.com")`. Declare the fields - # with their labels and section classes on the section: + # with their labels and section classes, and the has_many blocks, on the + # section: # # section :form, ActiveAdminPageObjects::Form do # field :email, "Email", ActiveAdminPageObjects::Form::StringField # field :status, "Status", ActiveAdminPageObjects::Form::SelectField + # has_many :line_items, "Line Items" do + # field :sku, "Sku", ActiveAdminPageObjects::Form::StringField + # end # end class Form < Section include SelectControl @@ -15,6 +19,18 @@ class Form < Section selector_key :form + class << self + # Declares the has_many block +name+ with its +heading+ (nil for + # `heading: false`). The block declares the fields of each fieldset. + # +name+ is the association. +visible+ is the Capybara option the block + # is found with. + def has_many(name, heading, visible: nil, &) + fieldsets = Class.new(HasMany::Fieldset, &) + type = Class.new(HasMany) { self.fieldset_class = fieldsets } + declare_typed(:has_many, name, heading, type: type, kind: :has_many, visible: visible) + end + end + # One `li.input` wrapper of the form. `Form#field` returns the declared # class, or the gem's subclass for the wrapper's formtastic class, or this # class. The wrapper is visible unless the lookup says otherwise, and so is @@ -106,6 +122,20 @@ def submit find(:active_admin, :form_submit, match: :first).click end + # The `has_many` block of +association+, e.g. `has_many(:line_items)`. A form + # that declares has_many blocks takes the declared name. A hidden block is + # found with `visible: :all`. + # @raise [ArgumentError] when has_many blocks are declared and +association+ is not one of them + # @return [HasMany] + def has_many(association, visible: nil) + declared = self.class.declarations.select { |_name, declaration| declaration[:kind] == :has_many } + declaration = Declarations.lookup(declared, association) + visibility = Declarations.visibility(declaration, visible) + return HasMany.new(self, find(:css, sel(:has_many, association.to_s), **visibility)) unless declaration + + declaration[:type].new(self, find(:css, sel(:has_many, slug(association)), **visibility)) + end + # True when the base-error list shows every one of +messages+ (or any # error when none are given). A String matches a whole error; a Regexp # matches part of one: `/can't be blank/`. @@ -168,6 +198,30 @@ def exact_semantic_errors?(messages, strict_order) @last_semantic_errors = actual strict_order ? actual == expected : actual.sort == expected.sort end + + # The heading of a declared has_many block: nil without the block, "" when it has no heading. + def declared_label_text(name, declaration, **visibility) + return super unless declaration[:kind] == :has_many + + container = sel(:has_many, name) + return unless first(:css, container, minimum: 0, wait: false, **visibility) + + label_text("#{container} > #{sel(:has_many_heading)}", **visibility).to_s + end + + # The fields outside the has_many blocks, and one entry per has_many block. + def page_element_keys(**visibility) + super + has_many_keys(**visibility) + end + + # The associations of the has_many blocks, without the ones nested in a + # fieldset: the hidden ones too, so that query takes every block. + def has_many_keys(**visibility) + every = all(:active_admin, :has_many_container, visible: :all, wait: false) + nested = every.flat_map { |node| node.all(:active_admin, :has_many_container, visible: :all, wait: false).to_a } + containers = all(:active_admin, :has_many_container, wait: false, **visibility) + [containers, nested].map { |nodes| nodes.map { |node| node["data-has-many-association"] } }.reduce(:-).uniq + end end end diff --git a/lib/active_admin_page_objects/has_many.rb b/lib/active_admin_page_objects/has_many.rb new file mode 100644 index 0000000..5b0ba2a --- /dev/null +++ b/lib/active_admin_page_objects/has_many.rb @@ -0,0 +1,104 @@ +# frozen_string_literal: true + +module ActiveAdminPageObjects + # A `has_many` block of a resource form, with the fieldsets of its nested + # records. Reached with `form.has_many(:line_items)`. + class HasMany < Section + selector_key :has_many + + class << self + # Sets the section class of the fieldsets. A has_many declared on a form + # sets the class built from its block. + attr_writer :fieldset_class + + # The section class of the fieldsets. + # @return [Class] + def fieldset_class + @fieldset_class || (superclass.respond_to?(:fieldset_class) ? superclass.fieldset_class : Fieldset) + end + end + + # One nested record's fieldset. Fields are named and typed like the + # form's: see Fields. A has_many block nested in the fieldset is not one + # of its fields. + class Fieldset < Section + include SelectControl + include Fields + + # Removes a new, unsaved fieldset, or ticks the delete checkbox of a saved one. + # @raise [ArgumentError] when the fieldset has neither + def remove + if has_css?(sel(:has_many_remove), wait: false) + find(:active_admin, :has_many_remove).click + elsif has_css?(sel(:has_many_delete), wait: false) + find(:active_admin, :has_many_delete).check + else + raise ArgumentError, "the fieldset has no remove link and no delete checkbox" + end + end + + # True when the delete checkbox of a saved record is ticked. + def marked_for_destroy? + has_css?(sel(:has_many_delete), wait: false) && find(:active_admin, :has_many_delete).checked? + end + + private + + # Formtastic ids a field ``, so the prefix of + # `order[line_items_attributes][0][sku]` is `order_line_items_attributes_0`. + # A check_boxes or multiple select name ends in `[]` after the attribute. + def field_prefix + first_control_name.delete_suffix("[]").sub(/\[[^\]]*\]\z/, "").tr("[", "_").delete("]") + end + end + + # The block heading. + # @return [String] + def heading + find(:css, sel(:has_many_heading), match: :first).text.strip + end + + # The number of fieldsets. + # @return [Integer] + def count + all(:active_admin, :has_many_fieldset, wait: false).size + end + + # All fieldsets, in page order. + # @return [Array
] + def fieldsets + all(:active_admin, :has_many_fieldset, wait: false).map { |node| self.class.fieldset_class.new(self, node) } + end + + # The fieldset at +index+ (0-based), waiting for it to appear. + # @return [Fieldset] + def fieldset(index) + self.class.fieldset_class.new(self, all(:active_admin, :has_many_fieldset, minimum: index + 1)[index]) + end + + # Clicks the add link, waits for the new fieldset and returns it. + # @return [Fieldset] + def add + before = count + find(:active_admin, :has_many_add).click + fieldset(before) + end + + # Removes the fieldset at +index+: a new one with its remove link, a saved + # one by ticking its delete checkbox. + # @raise [ArgumentError] when the fieldset has neither + def remove(index) + fieldset(index).remove + end + + # True when there are +count+ fieldsets, or any when +count+ is nil. + def has_fieldsets?(count: nil, **options) + has_css?(sel(:has_many_fieldset), **given(count: count), **options) + end + + # Waits until there are no fieldsets, or not +count+ fieldsets. + def has_no_fieldsets?(count: nil, **options) + has_no_css?(sel(:has_many_fieldset), **given(count: count), **options) + end + end +end diff --git a/lib/active_admin_page_objects/panel.rb b/lib/active_admin_page_objects/panel.rb index 9d55998..b250d64 100644 --- a/lib/active_admin_page_objects/panel.rb +++ b/lib/active_admin_page_objects/panel.rb @@ -10,16 +10,17 @@ module ActiveAdminPageObjects class Panel < Section selector_key :panel - # The panel title text. + # The panel title text. The panel's own title and body come before those + # of a panel nested in its body. # @return [String] def title - find(:active_admin, :panel_title).text.strip + find(:active_admin, :panel_title, match: :first).text.strip end # The panel body node, for content assertions. # @return [Capybara::Node::Element] def body - find(:active_admin, :panel_body) + find(:active_admin, :panel_body, match: :first) end # The links in the body: the text and the `href` attribute as written. diff --git a/lib/active_admin_page_objects/selectors.rb b/lib/active_admin_page_objects/selectors.rb index ab4c9dd..3586a84 100644 --- a/lib/active_admin_page_objects/selectors.rb +++ b/lib/active_admin_page_objects/selectors.rb @@ -40,6 +40,12 @@ module Selectors # The cells of the actions column at a 1-based column position. table_actions_cell: "tbody > tr > td:nth-child(%s) .data-table-resource-actions", table_row_actions_cell: "td:has(.data-table-resource-actions)", + table_sortable_header: 'thead th[data-column="%s"][data-sortable]', + table_sorted_header: 'thead th[data-column="%s"][data-sort-direction]', + table_sorted_header_in: 'thead th[data-column="%s"][data-sort-direction="%s"]', + table_sort_link: "a", + status_tag: ".status-tag", + status_tag_with_status: '[data-status="%s"]', blank_slate: ".main-content-container .border-dashed", attributes_table: ".attributes-table", @@ -79,9 +85,16 @@ module Selectors batch_actions_button: ".batch-actions-dropdown-toggle", batch_action_item: "[data-batch-action-item]", - form: "form.formtastic", + form: "form.formtastic:not(.active_admin_comment)", # Hidden inputs are not fields. - form_input_wrapper: "li.input:not(.hidden)", + form_input_wrapper: "li.input:not(.hidden):not(.has-many-delete)", + has_many_container: ".has-many-container", + has_many: '.has-many-container[data-has-many-association="%s"]', + has_many_heading: "h3.has-many-fields-title", + has_many_fieldset: "fieldset.has-many-fields", + has_many_add: "a.has-many-add", + has_many_remove: "a.has-many-remove", + has_many_delete: "li.has-many-delete input[type=checkbox]", form_input: "li#%s_%s_input", form_choice: "li.choice label", # The hidden input of a boolean or check_boxes wrapper is not a control. @@ -89,6 +102,15 @@ module Selectors form_inline_error: ".inline-errors", form_semantic_error: "ul.errors > li", form_submit: "fieldset.actions input[type=submit], fieldset.actions button[type=submit]", + comments: "#active-admin-comments-form", + # The comments block has two bold titles: "Comments", then "All Comments (N)". + comments_title: "div.font-bold:not(:first-child)", + comment: "[data-test-comment-container]", + comment_body: "[data-test-comment-container] > div:nth-child(2)", + comment_author: "[data-test-comment-container] > div:first-child > span:first-child", + comment_delete: '[data-test-comment-container] > a[data-method="delete"]', + comment_input: 'textarea[name="comment[body]"]', + comment_submit: "form fieldset.actions input[type=submit], form fieldset.actions button[type=submit]", tabs: REMOVED }.freeze diff --git a/lib/active_admin_page_objects/status_tag.rb b/lib/active_admin_page_objects/status_tag.rb new file mode 100644 index 0000000..91ecc21 --- /dev/null +++ b/lib/active_admin_page_objects/status_tag.rb @@ -0,0 +1,141 @@ +# frozen_string_literal: true + +module ActiveAdminPageObjects + # A `status_tag`: `Pending`. + # Reached with `row.status_tag(:status)` on an index row or + # `attributes_table.status_tag(:status)` on a show page. A cell with several + # tags gives them with `status_tags(:status)`. + class StatusTag < Section + selector_key :status_tag + + # The status tags of a cell, for the sections whose cells hold them. The + # section names a cell by a key: it has `cell_selector(key)`, and + # `visibility_of(key, visible)` from Declarations::Lookup. + module Matchers + # The status tag in the cell of +key+. + # @raise [Capybara::Ambiguous] when the cell has several: see #status_tags + # @return [StatusTag] + def status_tag(key, visible: nil) + visibility = visibility_of(key, visible) + StatusTag.new(self, find(:css, status_tag_selector(key), **visibility)) + end + + # Every status tag in the cell of +key+, in page order. + # @return [Array] + def status_tags(key, visible: nil) + all(:css, status_tag_selector(key), **visibility_of(key, visible)).map { |node| StatusTag.new(self, node) } + end + + # True when the cell of +key+ has a status tag with the Capybara options. + # +label+ is the whole text of the tag, ignoring case: a Regexp matches + # part of it. +status+ is the tag's `data-status`, e.g. :pending, or + # true for "yes" and false for "no". `type:` is another name for `status:`. + # @raise [ArgumentError] when both `status:` and `type:` are given, or one + # is not a String, a Symbol, true or false + def has_status_tag?(key, label = nil, status: nil, type: nil, **options) + css, query = status_tag_query(key, label, status, type, options) + has_css?(css, **query) + end + + # Waits until the cell of +key+ has no such status tag. + # @raise [ArgumentError] as #has_status_tag? does + def has_no_status_tag?(key, label = nil, status: nil, type: nil, **options) + css, query = status_tag_query(key, label, status, type, options) + has_no_css?(css, **query) + end + + private + + def status_tag_selector(key, status = nil) + base = "#{cell_selector(key)} #{sel(:status_tag)}" + status.nil? ? base : "#{base}#{sel(:status_tag_with_status, Capybara::Selector::CSS.escape(status))}" + end + + # The CSS and the Capybara options of a status tag lookup. A status + # that is not one of the accepted kinds would match no tag, so + # `has_no_status_tag?` would pass. + def status_tag_query(key, label, status, type, options) + raise ArgumentError, "give status: or type:, not both" unless status.nil? || type.nil? + + status = StatusTag.status_value(status.nil? ? type : status) + css = status_tag_selector(key, status) + [css, { **visibility_of(key), **case_insensitive_text(status_tag_label(label, options)) }] + end + + def status_tag_label(label, options) + return options if label.nil? + + label.is_a?(Regexp) ? options.except(:exact_text).merge(text: label) : options.except(:text).merge(exact_text: label) + end + end + + class << self + # The `data-status` value of +status+: nil for none, "yes" for true and + # "no" for false, as ActiveAdmin writes them. + # @api private + # @raise [ArgumentError] when +status+ is not nil, a String, a Symbol, true or false + # @return [String, nil] + def status_value(status) + case status + when nil then nil + when true then "yes" + when false then "no" + when String, Symbol then status.to_s + else raise ArgumentError, "status must be a String, a Symbol, true or false, got #{status.inspect}" + end + end + end + + # The tag text as rendered in the DOM, e.g. "Pending", before any CSS + # `text-transform`. + # @return [String] + def label + squish(root_element.text(:all)) + end + + # The tag's `data-status`, e.g. "pending", or nil when it has none. + # @return [String, nil] + def status + value = root_element[:"data-status"].to_s + value.empty? ? nil : value + end + + # True when the tag's `data-status` is +status+ (see Matchers#has_status_tag?). + # @raise [ArgumentError] when +status+ is not a String, a Symbol, true or false + def has_status?(status, **options) + wanted = self.class.status_value(status) + raise ArgumentError, "status must be given" if wanted.nil? + + eventually(**options) { self.status == wanted } + end + + # Waits until the tag's `data-status` is not +status+. + # @raise [ArgumentError] as #has_status? does + def has_no_status?(status, **options) + wanted = self.class.status_value(status) + raise ArgumentError, "status must be given" if wanted.nil? + + eventually(**options) { self.status != wanted } + end + + # True when the label equals +text+, ignoring case. + def has_label?(text, **options) + eventually(**options) { same_text?(label, text) } + end + + # Waits until the label differs from +text+. + def has_no_label?(text, **options) + eventually(**options) { !same_text?(label, text) } + end + end + + class Table < Section + class Row < Section + include StatusTag::Matchers + end + end + + class AttributesTable < Section + include StatusTag::Matchers + end +end diff --git a/lib/active_admin_page_objects/table.rb b/lib/active_admin_page_objects/table.rb index e07482d..5ab3398 100644 --- a/lib/active_admin_page_objects/table.rb +++ b/lib/active_admin_page_objects/table.rb @@ -193,5 +193,108 @@ def untitled_header_label(key, **visibility) header = keyed_headers(**visibility).assoc(key)&.last header && squish(header.text(:all)) end + + # Sorting by the header links. Included below the class body. + module Sorting + # True when the header of column +key+ is sortable. + def has_sortable_column?(key, **options) + has_css?(sortable_header_selector(key), **visibility_of(key), **options) + end + + # Waits until the header of column +key+ is not sortable. + def has_no_sortable_column?(key, **options) + has_no_css?(sortable_header_selector(key), **visibility_of(key), **options) + end + + # The direction the table is sorted by column +key+ in, or nil when it is + # not sorted by it. Does not wait. + # @return [Symbol, nil] :asc, :desc or nil + def sort_direction(key) + header = first(:css, sel(:table_column_header, slug(key)), minimum: 0, wait: false, **visibility_of(key)) + direction = header && header[:"data-sort-direction"].to_s + direction.to_sym unless direction.nil? || direction.empty? + end + + # True when the table is sorted by column +key+, in +direction+ (:asc or + # :desc) when given. + # @raise [ArgumentError] when +direction+ is neither :asc nor :desc + def has_sort?(key, direction = nil, **options) + has_css?(sorted_header_selector(key, direction), **visibility_of(key), **options) + end + + # Waits until the table is not sorted by column +key+, in +direction+ when given. + # @raise [ArgumentError] when +direction+ is neither :asc nor :desc + def has_no_sort?(key, direction = nil, **options) + has_no_css?(sorted_header_selector(key, direction), **visibility_of(key), **options) + end + alias sorted_by? has_sort? + alias not_sorted_by? has_no_sort? + + # Clicks the header link of column +key+ and waits for the page to show the + # new order. The link flips the direction, and an unsorted column sorts + # :desc first. With +direction+ it clicks until the column shows it, at + # most twice, and not at all when it already does. + # @raise [ArgumentError] when +direction+ is neither :asc nor :desc, or the column is not sortable + # @raise [Capybara::ExpectationNotMet] when the page does not show the direction in time + # @return [Symbol] the direction the column is sorted in + def sort_by(key, direction = nil) + wanted = sort_direction_name(direction) + (wanted ? 2 : 1).times do + header = sortable_header(key) + break if wanted && header[:"data-sort-direction"].to_s == wanted + + click_sort_link(key, header) + end + shown = sort_direction(key) + raise Capybara::ExpectationNotMet, "#{key.inspect} is not sorted #{wanted}" if wanted && shown.to_s != wanted + + shown + end + + private + + def sort_direction_name(direction) + return if direction.nil? + return direction.to_s if %w[asc desc].include?(direction.to_s) + + raise ArgumentError, "sort direction must be :asc or :desc, got #{direction.inspect}" + end + + def sortable_header_selector(key) + declaration_for(key) + sel(:table_sortable_header, slug(key)) + end + + def sorted_header_selector(key, direction) + declaration_for(key) + name = sort_direction_name(direction) + name ? sel(:table_sorted_header_in, slug(key), name) : sel(:table_sorted_header, slug(key)) + end + + # The header of column +key+, found with a wait. + def sortable_header(key) + header = find(:css, sel(:table_column_header, slug(key)), **visibility_of(key)) + return header if has_css?(sortable_header_selector(key), wait: false, **visibility_of(key)) + + raise ArgumentError, "#{key.inspect} is not a sortable column" + end + + def click_sort_link(key, header) + link = header.find(:css, sel(:table_sort_link)) + direction = link_direction(link) + raise ArgumentError, "the header link of #{key.inspect} has no order param" unless direction + + link.click + raise Capybara::ExpectationNotMet, "#{key.inspect} is not sorted #{direction}" unless has_sort?(key, direction) + end + + # The link's `order` param ends in the direction the click sorts by. + def link_direction(link) + query = href_attribute(link).partition("?").last + URI.decode_www_form(query).to_h["order"].to_s[/_(asc|desc)\z/, 1] + end + end + + include Sorting end end diff --git a/spec/active_admin_page_objects/attributes_table_spec.rb b/spec/active_admin_page_objects/attributes_table_spec.rb index 0143d32..e8adede 100644 --- a/spec/active_admin_page_objects/attributes_table_spec.rb +++ b/spec/active_admin_page_objects/attributes_table_spec.rb @@ -133,7 +133,7 @@ def declared_table(&) expect(declared.class.declarations).to include("name" => { label: "Name" }, "email" => { label: "Email", visible: :all }) expect(declared.row(:email)[:"data-row"]).to eq("email") expect(declared.value(:email)).to eq(customer.email) - expect(declared.value(:status)).to eq("active") + expect(declared.value(:status)).to eq("Active") expect(declared).to have_row(:email, exact_text: customer.email) expect(declared).to have_declared_rows expect(declared).to have_exact_rows(only: %i[name email]) diff --git a/spec/active_admin_page_objects/comments_spec.rb b/spec/active_admin_page_objects/comments_spec.rb new file mode 100644 index 0000000..1f56843 --- /dev/null +++ b/spec/active_admin_page_objects/comments_spec.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +RSpec.describe ActiveAdminPageObjects::Comments do + let(:page_class) do + Class.new(ActiveAdminPageObjects::Page) do + set_url "/admin/documents/{id}" + + section :comments, ActiveAdminPageObjects::Comments + end + end + let(:show) { page_class.new } + let(:document) { create_document } + + before { ActiveAdmin::Comment.delete_all } + + def create_comment(body) + author = AdminUser.find_or_create_by!(name: "Demo Admin") + ActiveAdmin::Comment.create!(namespace: "admin", resource: document, author: author, body: body) + end + + it "is empty without comments" do + show.load(id: document.id) + + expect(show.comments.count).to eq(0) + expect(show.comments.bodies).to eq([]) + expect(show.comments.authors).to eq([]) + expect(show.comments).to have_no_comment("First comment", wait: 0) + end + + it "adds a comment" do + show.load(id: document.id) + show.comments.add("First comment") + + expect(show.comments).to have_comment("First comment") + expect(show.comments.count).to eq(1) + expect(show.comments.bodies).to eq(["First comment"]) + expect(show.comments.authors).to eq(["Demo Admin"]) + expect(ActiveAdmin::Comment.pluck(:body)).to eq(["First comment"]) + end + + it "reads existing comments" do + create_comment("First comment") + create_comment("Second comment") + show.load(id: document.id) + + expect(show.comments.count).to eq(2) + expect(show.comments.bodies).to eq(["First comment", "Second comment"]) + expect(show.comments.authors).to eq(["Demo Admin", "Demo Admin"]) + expect(show.comments).to have_comment("Second") + expect(show.comments).to have_no_comment("Third", wait: 0) + end + + it "deletes a comment by its body" do + create_comment("First comment") + create_comment("Second comment") + show.load(id: document.id) + show.comments.delete("First comment") + + expect(show.comments).to have_no_comment("First comment") + expect(show.comments.bodies).to eq(["Second comment"]) + expect(show.comments.count).to eq(1) + expect(ActiveAdmin::Comment.pluck(:body)).to eq(["Second comment"]) + end + + it "raises when no comment has the text to delete" do + create_comment("First comment") + show.load(id: document.id) + + expect { show.comments.delete("Missing") }.to raise_error(Capybara::ElementNotFound, /Missing/) + end + + context "with rack_test", driver: :rack_test do + it "reads existing comments" do + create_comment("First comment") + show.load(id: document.id) + + expect(show.comments.count).to eq(1) + expect(show.comments.bodies).to eq(["First comment"]) + expect(show.comments.authors).to eq(["Demo Admin"]) + end + end +end diff --git a/spec/active_admin_page_objects/has_many_spec.rb b/spec/active_admin_page_objects/has_many_spec.rb new file mode 100644 index 0000000..555d1bf --- /dev/null +++ b/spec/active_admin_page_objects/has_many_spec.rb @@ -0,0 +1,305 @@ +# frozen_string_literal: true + +RSpec.describe ActiveAdminPageObjects::HasMany do + let(:form_page) { Pages::OrderForm.new } + let(:form) { form_page.form } + let(:line_items) { form.has_many(:line_items) } + let(:customer) { create_customer } + let(:order) { Order.create!(customer: customer, reference: "ORD-1", state: "new", quantity: 1) } + + def create_line_item(sku, kind, quantity) + LineItem.create!(order: order, sku: sku, kind: kind, quantity: quantity) + end + + # A form over the page's element, with the fields and has_many blocks the block declares. + def declared_form(&) + Class.new(ActiveAdminPageObjects::Form, &).new(form_page, form.root_element) + end + + # The line_items has_many of the form, with the fieldset fields the block declares. + def declared_line_items(&) + declared_form { has_many(:line_items, "Line Items", &) }.has_many(:line_items) + end + + shared_examples "saved fieldsets" do + before do + create_line_item("SKU-1", "Goods", 2) + create_line_item("SKU-B1", "Service", 1) + form_page.load(id: order.id, action: "edit") + end + + it "reads the heading and counts the fieldsets" do + expect(line_items.heading).to eq("Line Items") + expect(line_items.count).to eq(2) + expect(line_items.fieldsets.size).to eq(2) + expect(line_items).to have_fieldsets(count: 2) + expect(line_items).to have_no_fieldsets(count: 3) + end + + it "reads the declared fields of a fieldset by index" do + expect(line_items.fieldset(0).field(:sku)).to have_field(with: "SKU-1") + expect(line_items.fieldset(1).field(:sku).value).to eq("SKU-B1") + expect(line_items.fieldset(0).field(:quantity).value).to eq("2") + expect(line_items.fieldset(0).field(:quantity)).to be_an_instance_of(ActiveAdminPageObjects::Form::StringField) + expect(line_items.fieldset(0).field(:kind).selected).to eq("Goods") + expect(line_items.fieldsets.map { |fieldset| fieldset.field(:sku).value }).to eq(%w[SKU-1 SKU-B1]) + expect { line_items.fieldset(0).field(:price) } + .to raise_error(ArgumentError, /:price is not declared; declared keys: sku, kind, quantity/) + end + + it "types the fields of an undeclared has_many by the page" do + fieldset = ActiveAdminPageObjects::Form.new(form_page, form.root_element).has_many(:line_items).fieldset(0) + expect(fieldset).to be_an_instance_of(described_class::Fieldset) + expect(fieldset.field(:sku)).to be_an_instance_of(ActiveAdminPageObjects::Form::StringField) + expect(fieldset.field(:kind)).to be_an_instance_of(ActiveAdminPageObjects::Form::SelectField) + expect { fieldset.has_exact_fields? }.to raise_error(ArgumentError, /declares no labels/) + end + + it "has the declared fields in each fieldset and no other" do + expect(line_items).to have_fieldsets(count: 2) + expect(line_items.fieldsets).to all(have_declared_fields) + expect(line_items.fieldsets).to all(have_exact_fields) + expect(line_items.fieldset(1).exact_mismatches).to eq(missing: [], unexpected: [], labels: {}) + end + + it "reports the fieldset fields that differ from the declared ones" do + partial = declared_line_items do + field :sku, "Code", ActiveAdminPageObjects::Form::StringField + field :kind, "Kind", ActiveAdminPageObjects::Form::SelectField + field :price, "Price", ActiveAdminPageObjects::Form::StringField + end + fieldset = partial.fieldset(0) + expect(fieldset.field(:sku).value).to eq("SKU-1") + expect(fieldset).to have_no_exact_fields + expect(fieldset).to have_no_declared_fields + expect(fieldset.declared_label_mismatches).to eq("sku" => "Sku", "price" => nil) + expect(fieldset.exact_mismatches).to eq(missing: ["price"], unexpected: ["quantity"], labels: { "sku" => "Sku" }) + expect(fieldset).to have_exact_fields(only: :kind) + expect(fieldset).to have_declared_fields(except: %i[sku price]) + end + + it "builds the class a fieldset field is declared with" do + select_class = Class.new(ActiveAdminPageObjects::Form::SelectField) + typed = declared_line_items do + field :kind, "Kind", select_class + field :sku, "Sku", ActiveAdminPageObjects::Form::SelectField + end + expect(typed.fieldset(0).field(:kind)).to be_an_instance_of(select_class) + expect { typed.fieldset(0).field(:sku) } + .to raise_error(ActiveAdminPageObjects::DeclaredClassMismatch, /SelectField, but the page has .*StringField/) + end + + it "compares the inline errors of a fieldset" do + line_items.fieldset(1).fill(sku: "SKU-B2", quantity: 0) + form.submit + + expect(form).to have_field_errors + expect(form).to have_exact_field_errors + expect(line_items.fieldset(0)).to have_no_field_errors + expect(line_items.fieldset(0)).to have_exact_field_errors + expect(line_items.fieldset(1)).to have_field_errors + expect(line_items.fieldset(1)).to have_field_error(:quantity, "must be greater than 0") + expect(line_items.fieldset(1)).to have_no_field_error(:sku) + expect(line_items.fieldset(1)).to have_exact_field_errors(quantity: "must be greater than 0") + expect(line_items.fieldset(1)).to have_no_exact_field_errors + expect(line_items.fieldset(1)).to have_no_exact_field_errors(sku: "must be greater than 0") + Capybara.using_wait_time(0) { expect(form.has_no_field_errors?).to be(false) } + end + end + + it_behaves_like "saved fieldsets" + + context "with rack_test", driver: :rack_test do + it_behaves_like "saved fieldsets" + end + + context "when editing an order with two line items" do + before do + create_line_item("SKU-1", "Goods", 2) + create_line_item("SKU-B1", "Service", 1) + form_page.load(id: order.id, action: "edit") + end + + it "adds a fieldset, fills it and saves the line item" do + fieldset = line_items.add + expect(line_items).to have_fieldsets(count: 3) + expect(fieldset).to have_exact_fields + fieldset.fill(sku: "SKU-NEW", kind: "Service", quantity: 5) + form.submit + + expect(form_page.flashes).to have_flash(:notice, "Order was successfully updated.") + expect(order.line_items.pluck(:sku)).to match_array(%w[SKU-1 SKU-B1 SKU-NEW]) + expect(order.line_items.find_by(sku: "SKU-NEW")).to have_attributes(kind: "Service", quantity: 5) + end + + it "leaves a hidden fieldset field out unless it is declared or queried with visible: :all" do + hide("#order_line_items_attributes_0_quantity_input") + fieldset = line_items.fieldset(0) + Capybara.using_wait_time(0) do + expect { fieldset.field(:quantity) }.to raise_error(Capybara::ElementNotFound) + expect(fieldset.has_exact_fields?).to be(false) + end + expect(fieldset.exact_mismatches).to eq(missing: ["quantity"], unexpected: [], labels: {}) + expect(fieldset.field(:quantity, visible: :all)).to be_an_instance_of(ActiveAdminPageObjects::Form::StringField) + expect(fieldset).to have_exact_fields(visible: :all) + expect(line_items.fieldset(1)).to have_exact_fields + + partial = declared_line_items { field :sku, "Sku", ActiveAdminPageObjects::Form::StringField }.fieldset(0) + expect(partial.exact_mismatches[:unexpected]).to eq(["kind"]) + expect(partial.exact_mismatches(visible: :all)[:unexpected]).to eq(%w[kind quantity]) + + declared = declared_line_items do + field :sku, "Sku", ActiveAdminPageObjects::Form::StringField + field :kind, "Kind", ActiveAdminPageObjects::Form::SelectField + field :quantity, "Quantity", ActiveAdminPageObjects::Form::StringField, visible: :all + end + expect(declared).to have_fieldsets(count: 2) + expect(declared.fieldsets).to all(have_exact_fields) + expect(declared.fieldset(0).field(:quantity)).to be_an_instance_of(ActiveAdminPageObjects::Form::StringField) + end + + it "removes a new fieldset with its remove link" do + line_items.add + expect(line_items).to have_fieldsets(count: 3) + line_items.remove(2) + expect(line_items).to have_fieldsets(count: 2) + end + + it "raises when a fieldset has neither a remove link nor a delete checkbox" do + page.execute_script("document.querySelectorAll('li.has-many-delete').forEach((node) => node.remove())") + expect { line_items.remove(0) }.to raise_error(ArgumentError, /no remove link and no delete checkbox/) + expect(line_items).to have_fieldsets(count: 2) + end + + it "marks a saved fieldset for deletion and destroys the line item on save" do + expect(line_items.fieldset(0)).not_to be_marked_for_destroy + line_items.remove(0) + expect(line_items.fieldset(0)).to be_marked_for_destroy + form.submit + + expect(form_page.flashes).to have_flash(:notice, "Order was successfully updated.") + expect(order.line_items.pluck(:sku)).to eq(["SKU-B1"]) + end + end + + # The dummy form puts a check_boxes input first for this order: its + # hidden input is named `order[line_items_attributes][0][tags][]`. + shared_examples "a fieldset that starts with a check_boxes input" do + let(:order) { Order.create!(customer: customer, reference: "LINE-TAGS") } + + # Found again on each call: the form is rendered anew after a submit. + def fieldset + ActiveAdminPageObjects::Form.new(form_page, form_page.form.root_element).has_many(:line_items).fieldset(0) + end + + before do + create_line_item("SKU-1", "Goods", 2) + form_page.load(id: order.id, action: "edit") + end + + it "finds the fields by the fieldset prefix" do + expect(fieldset.field(:tags)).to be_an_instance_of(ActiveAdminPageObjects::Form::CheckBoxesField) + expect(fieldset.field(:sku).value).to eq("SKU-1") + end + + it "sees the inline errors of the fieldset" do + fieldset.fill(quantity: 0) + form.submit + + expect(fieldset).to have_field_error(:quantity, "must be greater than 0") + expect(fieldset).to have_exact_field_errors(quantity: "must be greater than 0") + expect(fieldset.has_no_field_error?(:quantity, wait: 0)).to be(false) + Capybara.using_wait_time(0) { expect(fieldset.has_exact_field_errors?).to be(false) } + end + end + + it_behaves_like "a fieldset that starts with a check_boxes input" + + context "with rack_test and a leading check_boxes input", driver: :rack_test do + it_behaves_like "a fieldset that starts with a check_boxes input" + end + + context "when creating an order" do + before do + customer + form_page.load(action: "new") + end + + it "starts without fieldsets" do + expect(line_items.count).to eq(0) + expect(line_items).to have_no_fieldsets + end + + it "adds a fieldset and saves the order with its line item" do + form.fill(reference: "ORD-NEW", customer: customer.name) + line_items.add.field(:sku).fill("SKU-NEW") + line_items.add.fill(sku: "SKU-2", kind: "Service") + form.submit + + expect(form_page.flashes).to have_flash(:notice, "Order was successfully created.") + expect(Order.last.line_items.pluck(:sku)).to eq(%w[SKU-NEW SKU-2]) + end + end + + describe "the has_many block of the form" do + before { form_page.load(action: "new") } + + it "counts the block once, as its declared element" do + expect(form).to have_exact_fields + expect(form).to have_declared_fields + expect(form.exact_mismatches).to eq(missing: [], unexpected: [], labels: {}) + expect(form.declared_label_mismatches).to eq({}) + end + + it "does not count the inputs of its fieldsets" do + line_items.add + expect(form).to have_exact_fields + expect(form.exact_mismatches).to eq(missing: [], unexpected: [], labels: {}) + end + + it "reports a block that is not declared, or declared with another heading" do + fields = lambda do |heading| + declared_form do + field :reference, "Reference", ActiveAdminPageObjects::Form::StringField + field :state, "State", ActiveAdminPageObjects::Form::SelectField + field :quantity, "Quantity", ActiveAdminPageObjects::Form::StringField + field :customer, "Customer", ActiveAdminPageObjects::Form::SelectField + has_many :line_items, heading if heading + end + end + expect(fields.call(nil).exact_mismatches).to eq(missing: [], unexpected: ["line_items"], labels: {}) + expect(fields.call("Items").exact_mismatches).to eq(missing: [], unexpected: [], labels: { "line_items" => "Line Items" }) + end + + it "reports a declared block the page lacks" do + absent = declared_form { has_many :parts, "Parts" } + expect(absent.declared_label_mismatches).to eq("parts" => nil) + end + + it "is not a field" do + expect { form.field(:line_items) }.to raise_error(ArgumentError, /:line_items is declared as a has_many, not as a field/) + expect { form.has_many(:orders) }.to raise_error(ArgumentError, /:orders is not declared; declared keys: line_items/) + end + + it "is found when hidden only with visible: :all, or when declared with it" do + hide(".has-many-container") + Capybara.using_wait_time(0) do + expect { form.has_many(:line_items) }.to raise_error(Capybara::ElementNotFound) + expect(form.has_exact_fields?).to be(false) + end + expect(form.has_many(:line_items, visible: :all)).to be_a(described_class) + expect(form).to have_exact_fields(visible: :all) + expect(declared_form { has_many :line_items, "Line Items", visible: :all }.has_many(:line_items)).to be_a(described_class) + end + end + + describe ".fieldset_class" do + it "defaults to Fieldset and is inherited" do + custom = Class.new(described_class::Fieldset) + parent = Class.new(described_class) { self.fieldset_class = custom } + expect(described_class.fieldset_class).to eq(described_class::Fieldset) + expect(parent.fieldset_class).to eq(custom) + expect(Class.new(parent).fieldset_class).to eq(custom) + end + end +end diff --git a/spec/active_admin_page_objects/panel_spec.rb b/spec/active_admin_page_objects/panel_spec.rb index 22ee027..05a2424 100644 --- a/spec/active_admin_page_objects/panel_spec.rb +++ b/spec/active_admin_page_objects/panel_spec.rb @@ -18,6 +18,14 @@ ) expect(dashboard.panel("Stats").links).to eq([]) end + + it "tells a panel from the panel nested in it" do + dashboard = Pages::Dashboard.new + dashboard.load + expect(dashboard.panel("Inner stats").body).to have_text("Nested.") + expect(dashboard.panel("Overview").title).to eq("Overview") + expect(dashboard.panel("Inner stats").title).to eq("Inner stats") + end end it_behaves_like "panel links" diff --git a/spec/active_admin_page_objects/status_tag_spec.rb b/spec/active_admin_page_objects/status_tag_spec.rb new file mode 100644 index 0000000..317f34b --- /dev/null +++ b/spec/active_admin_page_objects/status_tag_spec.rb @@ -0,0 +1,132 @@ +# frozen_string_literal: true + +RSpec.describe ActiveAdminPageObjects::StatusTag do + let(:index) { Pages::CustomerIndex.new } + let(:show) { Pages::CustomerShow.new } + let!(:customer) { create_customer(status: "pending", active: false) } + let(:row) { index.table.row(customer.id) } + + shared_examples "status tags" do + describe "in an index row" do + before { index.load } + + it "reads a tag's label and status" do + tag = row.status_tag(:status) + expect(tag).to be_a(described_class) + expect(tag.label).to eq("Pending") + expect(tag.status).to eq("pending") + expect(row.status_tag(:active).status).to eq("no") + expect(row.status_tag(:active).label).to eq("No") + end + + it "compares a tag's status and label" do + tag = row.status_tag(:status) + expect(tag).to have_status(:pending) + expect(tag).to have_status("pending") + expect(tag).to have_no_status(:active) + expect(tag).to have_label("PENDING") + expect(tag).to have_no_label("Pend") + expect(tag.has_status?(:active, wait: 0)).to be(false) + expect(tag.has_no_status?(:pending, wait: 0)).to be(false) + expect(row.status_tag(:active)).to have_status(false) + expect { tag.has_status?(1) }.to raise_error(ArgumentError, /status must be a String, a Symbol/) + end + + it "has a status tag by label, status or both" do + expect(row).to have_status_tag(:status) + expect(row).to have_status_tag(:status, "Pending") + expect(row).to have_status_tag(:status, "PENDING") + expect(row).to have_status_tag("Status", /Pend/) + expect(row).to have_status_tag(:status, status: :pending) + expect(row).to have_status_tag(:status, "pending", status: "pending") + expect(row).to have_status_tag(:status, type: :pending) + expect(row).to have_status_tag(:active, "No", status: false) + expect(row).to have_status_tag(:active, status: :no) + end + + it "has no status tag when the label or the status differs" do + expect(row).to have_no_status_tag(:status, "Pend") + expect(row).to have_no_status_tag(:status, "Active") + expect(row).to have_no_status_tag(:status, status: :active) + expect(row).to have_no_status_tag(:status, type: :active) + expect(row).to have_no_status_tag(:status, "Pending", status: :active) + expect(row).to have_no_status_tag(:active, status: true) + expect(row).to have_no_status_tag(:name) + end + + it "does not wait for a tag that is there, or give a false pass" do + expect(row.has_status_tag?(:status, "Active", wait: 0)).to be(false) + expect(row.has_status_tag?(:status, status: :active, wait: 0)).to be(false) + expect(row.has_no_status_tag?(:status, "Pending", wait: 0)).to be(false) + expect(row.has_no_status_tag?(:status, status: :pending, wait: 0)).to be(false) + end + + it "passes Capybara options on" do + expect(row).to have_status_tag(:status, count: 1) + expect(row).to have_no_status_tag(:status, count: 2) + end + + it "rejects a call that would match nothing" do + expect { row.has_status_tag?(:status, status: :pending, type: :pending) } + .to raise_error(ArgumentError, /status: or type:, not both/) + expect { row.has_no_status_tag?(:status, status: :pending, type: :active) } + .to raise_error(ArgumentError, /status: or type:, not both/) + expect { row.has_no_status_tag?(:status, status: 1) }.to raise_error(ArgumentError, /status must be a String/) + expect { row.has_no_status_tag?(:status, type: Object.new) }.to raise_error(ArgumentError, /status must be a String/) + expect { row.has_status_tag?(:secret) }.to raise_error(ArgumentError, /:secret is not declared/) + expect { row.status_tag(:secret) }.to raise_error(ArgumentError, /:secret is not declared/) + end + + it "finds no tag in a cell without one" do + expect { row.status_tag(:name) }.to raise_error(Capybara::ElementNotFound) + expect(row.status_tags(:name)).to eq([]) + end + end + + describe "in a cell with several tags" do + let(:lenient_row) do + ActiveAdminPageObjects::Table.new(index, index.table.root_element).row(customer.id) + end + + before { index.load(query: { with_flags: 1 }) } + + it "lists the tags in page order" do + tags = lenient_row.status_tags(:flags) + expect(tags.map(&:status)).to eq(%w[pending no]) + expect(tags.map(&:label)).to eq(%w[Pending No]) + end + + it "is ambiguous for one tag, and has a tag when any matches" do + expect { lenient_row.status_tag(:flags) }.to raise_error(Capybara::Ambiguous) + expect(lenient_row).to have_status_tag(:flags, "No") + expect(lenient_row).to have_status_tag(:flags, status: :pending) + expect(lenient_row).to have_status_tag(:flags, count: 2) + expect(lenient_row).to have_no_status_tag(:flags, "Active") + end + end + + describe "on a show page" do + before { show.load(id: customer.id) } + + it "reads and compares the tag of a row" do + tag = show.attributes_table.status_tag(:status) + expect(tag.label).to eq("Pending") + expect(tag.status).to eq("pending") + expect(show.attributes_table.status_tags(:status).size).to eq(1) + expect(show.attributes_table).to have_status_tag(:status, "pending", status: :pending) + expect(show.attributes_table).to have_status_tag("Status", type: "pending") + expect(show.attributes_table).to have_no_status_tag(:status, "Active") + expect(show.attributes_table).to have_no_status_tag(:status, status: :active) + expect(show.attributes_table).to have_no_status_tag(:name) + expect { show.attributes_table.has_status_tag?(:secret) }.to raise_error(ArgumentError, /:secret is not declared/) + expect { show.attributes_table.has_status_tag?(:status, status: :a, type: :b) }.to raise_error(ArgumentError) + end + end + end + + it_behaves_like "status tags" + + context "with rack_test", driver: :rack_test do + it_behaves_like "status tags" + end +end diff --git a/spec/active_admin_page_objects/table_spec.rb b/spec/active_admin_page_objects/table_spec.rb index a2040b8..d071668 100644 --- a/spec/active_admin_page_objects/table_spec.rb +++ b/spec/active_admin_page_objects/table_spec.rb @@ -155,6 +155,75 @@ def declared_table(&) expect(table.has_row_with?(:name, "Nobody", wait: 0)).to be(false) expect { table.row_with(:name, "Nobody", wait: 0) }.to raise_error(Capybara::ElementNotFound, /no row with :name/) end + + it "tells the sortable columns" do + expect(table).to have_sortable_column(:name) + expect(table).to have_sortable_column("External ID") + expect(table).to have_sortable_column(:status) + expect(table).to have_sortable_column(:created) + expect(table).to have_no_sortable_column(:category) + expect(table).to have_no_sortable_column(:actions) + expect(table.has_sortable_column?(:category, wait: 0)).to be(false) + expect(table.has_no_sortable_column?(:name, wait: 0)).to be(false) + expect { table.has_sortable_column?(:secret) }.to raise_error(ArgumentError, /:secret is not declared/) + end + + it "shows the sort the page loads with" do + expect(table).to have_sort(:id) + expect(table).to have_sort(:id, :desc) + expect(table).to have_no_sort(:id, :asc) + expect(table).to have_no_sort(:name) + expect(table.sort_direction(:id)).to eq(:desc) + expect(table.sort_direction(:name)).to be_nil + expect(table.has_sort?(:id, :asc, wait: 0)).to be(false) + expect(table.has_no_sort?(:id, wait: 0)).to be(false) + expect { table.has_sort?(:id, :up) }.to raise_error(ArgumentError, /:asc or :desc/) + expect { table.has_no_sort?(:id, "") }.to raise_error(ArgumentError, /:asc or :desc/) + end + + describe "sorting" do + def sorted_names + index.table.rows.map { |row| row.cell(:name).text } + end + + it "follows the header link, which sorts an unsorted column descending first" do + expect(index.table.sort_by(:name)).to eq(:desc) + expect(index.table).to have_sort(:name, :desc) + expect(index.table).to have_no_sort(:id) + expect(sorted_names).to eq(customers.map(&:name).reverse) + expect(index.table.sort_by(:name)).to eq(:asc) + expect(sorted_names).to eq(customers.map(&:name)) + end + + it "clicks until the column shows the direction" do + index.table.sort_by(:name, :asc) + expect(index.table).to have_sort(:name, :asc) + expect(sorted_names).to eq(customers.map(&:name)) + index.table.sort_by(:name, :desc) + expect(index.table).to have_sort(:name, :desc) + expect(sorted_names).to eq(customers.map(&:name).reverse) + end + + it "does not click when the column already shows the direction" do + expect(index.table.sort_by(:id, :desc)).to eq(:desc) + expect(sorted_names).to eq(customers.map(&:name).reverse) + expect(index.table.sort_by(:id, "asc")).to eq(:asc) + expect(sorted_names).to eq(customers.map(&:name)) + end + + it "takes a column by its label and a sort key that differs from it" do + expect(index.table.sort_by("Created", :asc)).to eq(:asc) + expect(index.table).to have_sort(:created, :asc) + expect(index.table).to have_no_sort(:id) + end + + it "rejects a direction or a column it cannot sort by" do + expect { table.sort_by(:name, :up) }.to raise_error(ArgumentError, /:asc or :desc/) + expect { table.sort_by(:category) }.to raise_error(ArgumentError, /:category is not a sortable column/) + expect { table.sort_by(:secret) }.to raise_error(ArgumentError, /:secret is not declared/) + expect(table).to have_sort(:id, :desc) + end + end end it_behaves_like "index table" diff --git a/spec/dummy/app/admin/customers.rb b/spec/dummy/app/admin/customers.rb index cfb424d..a296ecf 100644 --- a/spec/dummy/app/admin/customers.rb +++ b/spec/dummy/app/admin/customers.rb @@ -44,12 +44,18 @@ column :name column :email column :external_id - column :status + column(:status) { |customer| status_tag customer.status } column :balance column :active column :category column "Created", :created_at column :notes if params[:with_notes] + if params[:with_flags] + column :flags do |customer| + status_tag customer.status + status_tag customer.active + end + end actions end @@ -58,7 +64,7 @@ row :name row :email row :external_id - row :status + row(:status) { |customer| status_tag customer.status } row :balance row :category row "Signed up", &:created_at diff --git a/spec/dummy/app/admin/dashboard.rb b/spec/dummy/app/admin/dashboard.rb index cfa4b07..26f8ce5 100644 --- a/spec/dummy/app/admin/dashboard.rb +++ b/spec/dummy/app/admin/dashboard.rb @@ -14,5 +14,10 @@ panel "Stats" do para "Nothing yet." end + panel "Overview" do + panel "Inner stats" do + para "Nested." + end + end end end diff --git a/spec/dummy/app/admin/documents.rb b/spec/dummy/app/admin/documents.rb index deb35c9..88a9d26 100644 --- a/spec/dummy/app/admin/documents.rb +++ b/spec/dummy/app/admin/documents.rb @@ -2,9 +2,10 @@ # Not in the menu. It holds what the customer pages cannot take without # changing their declared elements: a file input, disabled inputs and a -# title with a count. +# title with a count, and the comments. ActiveAdmin.register Document do menu false + config.comments = true permit_params :name, :attachment, :state, :kind, :code, :archived filter :name @@ -22,6 +23,7 @@ panel "Possible Routes (2)" do para "Two routes." end + active_admin_comments_for(resource) end form do |f| diff --git a/spec/dummy/app/admin/orders.rb b/spec/dummy/app/admin/orders.rb index 04f32e7..89f3ee1 100644 --- a/spec/dummy/app/admin/orders.rb +++ b/spec/dummy/app/admin/orders.rb @@ -3,6 +3,9 @@ ActiveAdmin.register Order do menu parent: "Catalog" + permit_params :reference, :state, :quantity, :customer_id, + line_items_attributes: [:id, :sku, :kind, :quantity, :_destroy, { tags: [] }] + filter :reference, filters: %i[not_eq eq] filter :quantity filter :customer @@ -15,4 +18,22 @@ column :quantity column :customer end + + form do |f| + f.semantic_errors + f.inputs do + f.input :reference + f.input :state, as: :select, collection: Order::STATES + f.input :quantity + f.input :customer, as: :select + end + f.has_many :line_items, heading: "Line Items", allow_destroy: true do |item| + # A check_boxes input first: its hidden input is named `...[tags][]`. + item.input :tags, as: :check_boxes, collection: %w[Gift Rush] if f.object.reference == "LINE-TAGS" + item.input :sku + item.input :kind, as: :select, collection: LineItem::KINDS + item.input :quantity + end + f.actions + end end diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb index bd54468..2d4239a 100644 --- a/spec/dummy/app/controllers/application_controller.rb +++ b/spec/dummy/app/controllers/application_controller.rb @@ -1,13 +1,9 @@ # frozen_string_literal: true class ApplicationController < ActionController::Base - DemoUser = Struct.new(:name) do - def to_s = name - end - private def current_admin_user - DemoUser.new("Demo Admin") + AdminUser.find_or_create_by!(name: "Demo Admin") end end diff --git a/spec/dummy/app/models/admin_user.rb b/spec/dummy/app/models/admin_user.rb new file mode 100644 index 0000000..fd53bc2 --- /dev/null +++ b/spec/dummy/app/models/admin_user.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +# The comment author: ActiveAdmin::Comment needs an ActiveRecord author. +class AdminUser < ActiveRecord::Base + def to_s = name +end diff --git a/spec/dummy/app/models/line_item.rb b/spec/dummy/app/models/line_item.rb new file mode 100644 index 0000000..6ff45d8 --- /dev/null +++ b/spec/dummy/app/models/line_item.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +class LineItem < ActiveRecord::Base + KINDS = %w[Goods Service].freeze + + belongs_to :order + + # Not stored: the form shows it as a check_boxes input. + attr_accessor :tags + + validates :quantity, numericality: { greater_than: 0, allow_nil: true } +end diff --git a/spec/dummy/app/models/order.rb b/spec/dummy/app/models/order.rb index 3b8557d..781e42a 100644 --- a/spec/dummy/app/models/order.rb +++ b/spec/dummy/app/models/order.rb @@ -4,6 +4,9 @@ class Order < ActiveRecord::Base STATES = %w[new paid shipped].freeze belongs_to :customer + has_many :line_items, dependent: :destroy + + accepts_nested_attributes_for :line_items, allow_destroy: true def self.ransackable_attributes(_auth = nil) = %w[reference state quantity customer_id] def self.ransackable_associations(_auth = nil) = %w[customer] diff --git a/spec/dummy/config/schema.rb b/spec/dummy/config/schema.rb index 6ec40e9..e292fb3 100644 --- a/spec/dummy/config/schema.rb +++ b/spec/dummy/config/schema.rb @@ -33,4 +33,23 @@ create_table :tags do |t| t.string :name end + + create_table :line_items do |t| + t.references :order + t.string :sku, :kind + t.integer :quantity + end + + create_table :active_admin_comments do |t| + t.string :namespace + t.text :body + t.references :resource, polymorphic: true + t.references :author, polymorphic: true + t.timestamps + end + add_index :active_admin_comments, :namespace + + create_table :admin_users do |t| + t.string :name + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bde6ef0..4885414 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -40,7 +40,7 @@ config.before do |example| Capybara.current_driver = example.metadata[:driver] || Capybara.default_driver - [Order, Customer, Category, Tag, Document].each(&:delete_all) + [LineItem, Order, Customer, Category, Tag, Document, ActiveAdmin::Comment].each(&:delete_all) end config.after do diff --git a/spec/support/pages.rb b/spec/support/pages.rb index c2086f0..7893559 100644 --- a/spec/support/pages.rb +++ b/spec/support/pages.rb @@ -125,4 +125,20 @@ class TagIndex < ActiveAdminPageObjects::Page section :table, ActiveAdminPageObjects::Table end + + class OrderForm < ActiveAdminPageObjects::Page + set_url "/admin/orders{/id}{/action}" + + section :form, ActiveAdminPageObjects::Form do + field :reference, "Reference", ActiveAdminPageObjects::Form::StringField + field :state, "State", ActiveAdminPageObjects::Form::SelectField + field :quantity, "Quantity", ActiveAdminPageObjects::Form::StringField + field :customer, "Customer", ActiveAdminPageObjects::Form::SelectField + has_many :line_items, "Line Items" do + field :sku, "Sku", ActiveAdminPageObjects::Form::StringField + field :kind, "Kind", ActiveAdminPageObjects::Form::SelectField + field :quantity, "Quantity", ActiveAdminPageObjects::Form::StringField + end + end + end end From d5531e40b7ea7257cc1e0ef9faa7b70b753fd4b1 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Tue, 1 Dec 2026 15:08:23 +0200 Subject: [PATCH 5/7] Bump the version to 2.0.0.beta1 60e84a9 and 8ec1677 both report 2.0.0.alpha, so a theme's check_version! cannot require the StatusTag section that only 8ec1677 has. Co-Authored-By: Clanker --- CHANGELOG.md | 4 ++-- lib/active_admin_page_objects/version.rb | 2 +- spec/active_admin_page_objects/text_spec.rb | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0b0075..bb115d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 2.0.0.alpha +## 2.0.0.beta1 ### Added @@ -40,7 +40,7 @@ - `Panel#links` lists the links of the body as `{ text:, href: }`, with the `href` attribute as the page wrote it. - `ActiveAdminPageObjects::RSpec::Matchers`, loaded with `require "active_admin_page_objects/rspec"`: the matcher names of capybara_active_admin 1.0.0, which call the predicate of a page object and that gem's matcher for anything else. - `MainMenu#labels(*parents)` lists the item labels at a menu level. `MainMenu#click(*labels)` opens each collapsed parent with its toggle button and clicks the item's link, as a user does; it sees visible items only, so a hidden submenu raises `Capybara::ElementNotFound`. `go` still visits the link's URL. -- Version 2.0.0.alpha: page objects for vanilla ActiveAdmin 4 only. The gem now depends on `activeadmin` (>= 4.0.0.beta1, < 5.0.0.a). Vanilla ActiveAdmin 3 moves to the 1.x line. +- Version 2.x: page objects for vanilla ActiveAdmin 4 only. The gem now depends on `activeadmin` (>= 4.0.0.beta1, < 5.0.0.a). Vanilla ActiveAdmin 3 moves to the 1.x line. - SitePrism page and sections for vanilla ActiveAdmin 4: layout, breadcrumbs, action items, flashes, main menu, index table, attributes table, panel, filters (string, numeric, select, boolean, date range), scopes, pagination, batch actions and formtastic forms. - `ActiveAdminPageObjects.register_selectors(**map)` takes only the selector map. It can also replace a key ActiveAdmin 4 removed, such as `tabs`. - `ActiveAdminPageObjects::Layout.add_section` and `Layout.add_element` add a section or an element to every page that includes `Layout`, including page classes defined earlier. diff --git a/lib/active_admin_page_objects/version.rb b/lib/active_admin_page_objects/version.rb index 61626f0..cce6ac5 100644 --- a/lib/active_admin_page_objects/version.rb +++ b/lib/active_admin_page_objects/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module ActiveAdminPageObjects - VERSION = "2.0.0.alpha" + VERSION = "2.0.0.beta1" end diff --git a/spec/active_admin_page_objects/text_spec.rb b/spec/active_admin_page_objects/text_spec.rb index 05beed2..8f3a0e6 100644 --- a/spec/active_admin_page_objects/text_spec.rb +++ b/spec/active_admin_page_objects/text_spec.rb @@ -68,6 +68,6 @@ end it "has a version" do - expect(ActiveAdminPageObjects::VERSION).to eq("2.0.0.alpha") + expect(ActiveAdminPageObjects::VERSION).to eq("2.0.0.beta1") end end From 01de59a47df760842fc6a6840a740e3f7253c2cd Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Tue, 1 Dec 2026 20:43:26 +0200 Subject: [PATCH 6/7] Fix the batch menu, selection cells and combined text options Covers the three findings of the first review on PR #1. Co-Authored-By: Clanker --- CHANGELOG.md | 4 +- .../batch_actions.rb | 3 +- lib/active_admin_page_objects/selectors.rb | 1 + lib/active_admin_page_objects/table.rb | 14 ++++++- .../table/rows_by_cell.rb | 3 +- lib/active_admin_page_objects/text.rb | 38 ++++++++++++------- .../batch_actions_spec.rb | 9 +++++ spec/active_admin_page_objects/table_spec.rb | 4 ++ spec/active_admin_page_objects/text_spec.rb | 7 ++++ 9 files changed, 64 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb115d7..98f75a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,9 @@ ### Added -- `Table::Row#cell(:actions)`, `has_cell?(:actions)` and `Table#row_with(:actions, ...)` find the actions cell. ActiveAdmin 4 writes no `data-column` on it, so these lookups used to fail. +- `Table::Row#cell`, `has_cell?` and `Table#row_with` find the cells of the `actions` and `selectable` columns. ActiveAdmin 4 writes no `data-column` on them, so these lookups used to fail. +- `BatchActions#apply` leaves an open menu open; clicking the toggle again closed it. +- A String `text:` together with a String `exact_text:` checks both, also in the case-insensitive cell and row matchers. - `Flashes#flash_types`, a private method that a theme overrides to add the flash types it renders. - `Comments` section for resource comments: `count`, `bodies`, `authors`, `has_comment?`, `add` and `delete`. The `form` selector leaves the comment form out. - has_many support: `Form.has_many`, `Form#has_many` and the `HasMany` section with fieldsets, `add`, `remove` and `marked_for_destroy?`. `have_exact_fields` counts a has_many block as one declared element, so a form with an undeclared has_many block reports it as unexpected. diff --git a/lib/active_admin_page_objects/batch_actions.rb b/lib/active_admin_page_objects/batch_actions.rb index 693947b..3814b05 100644 --- a/lib/active_admin_page_objects/batch_actions.rb +++ b/lib/active_admin_page_objects/batch_actions.rb @@ -15,7 +15,8 @@ def select_all # ("Delete Selected"), or with the batch-action name (`:destroy`). Accepts # the browser confirmation when the action has one. def apply(label) - find(:active_admin, :batch_actions_button).click + # The button toggles the menu, so leave an open menu open. + find(:active_admin, :batch_actions_button).click unless find_action_item(label)&.visible? item = action_item(label) if item[:"data-confirm"].to_s.empty? item.click diff --git a/lib/active_admin_page_objects/selectors.rb b/lib/active_admin_page_objects/selectors.rb index 3586a84..3622404 100644 --- a/lib/active_admin_page_objects/selectors.rb +++ b/lib/active_admin_page_objects/selectors.rb @@ -40,6 +40,7 @@ module Selectors # The cells of the actions column at a 1-based column position. table_actions_cell: "tbody > tr > td:nth-child(%s) .data-table-resource-actions", table_row_actions_cell: "td:has(.data-table-resource-actions)", + table_row_selection_cell: "td:has(input.batch-actions-resource-selection)", table_sortable_header: 'thead th[data-column="%s"][data-sortable]', table_sorted_header: 'thead th[data-column="%s"][data-sort-direction]', table_sorted_header_in: 'thead th[data-column="%s"][data-sort-direction="%s"]', diff --git a/lib/active_admin_page_objects/table.rb b/lib/active_admin_page_objects/table.rb index 5ab3398..8cdad26 100644 --- a/lib/active_admin_page_objects/table.rb +++ b/lib/active_admin_page_objects/table.rb @@ -29,6 +29,17 @@ def column(key, label, visible: nil) ACTIONS_COLUMN = "actions" private_constant :SELECTION_COLUMN, :ACTIONS_COLUMN + # The CSS of the body cells of column +column+, a #slug. The selection + # and actions cells are found by their content. + # @api private + def self.cell_css(column) + case column + when SELECTION_COLUMN then ActiveAdminPageObjects.selector(:table_row_selection_cell) + when ACTIONS_COLUMN then ActiveAdminPageObjects.selector(:table_row_actions_cell) + else ActiveAdminPageObjects.selector(:table_cell, column) + end + end + # One `` of the table body. class Row < Section include Declarations::Lookup @@ -71,8 +82,7 @@ def declaring_class def cell_selector(key) declaration_for(key) - column = slug(key) - column == ACTIONS_COLUMN ? sel(:table_row_actions_cell) : sel(:table_cell, column) + Table.cell_css(slug(key)) end end diff --git a/lib/active_admin_page_objects/table/rows_by_cell.rb b/lib/active_admin_page_objects/table/rows_by_cell.rb index 280974d..9e9f54d 100644 --- a/lib/active_admin_page_objects/table/rows_by_cell.rb +++ b/lib/active_admin_page_objects/table/rows_by_cell.rb @@ -32,8 +32,7 @@ def eventually_row(key, text, **options) def find_row_with(key, text) declaration_for(key) - column = slug(key) - cell_css = column == ACTIONS_COLUMN ? sel(:table_row_actions_cell) : sel(:table_cell, column) + cell_css = Table.cell_css(slug(key)) rows.find do |row| cell = row.first(:css, cell_css, minimum: 0, wait: false, **visibility_of(key)) cell && text_match?(cell.text, text) diff --git a/lib/active_admin_page_objects/text.rb b/lib/active_admin_page_objects/text.rb index 29cca32..5e99cb4 100644 --- a/lib/active_admin_page_objects/text.rb +++ b/lib/active_admin_page_objects/text.rb @@ -27,26 +27,38 @@ def text_match?(actual, expected) end # Capybara options with a String `text:` or `exact_text:` turned into a - # case-insensitive Regexp in `text:`. Chrome reports CSS-transformed text, - # so a tag uppercased by the theme still matches "verified". + # case-insensitive Regexp in `text:`; when both are set, the Regexp keeps + # both. Chrome reports CSS-transformed text, so a tag uppercased by the + # theme still matches "verified". # @return [Hash] def case_insensitive_text(options) text = options[:text] exact = options[:exact_text] - if exact.is_a?(String) && text.nil? - options.except(:exact_text).merge(text: text_pattern(exact, exact: true)) - elsif text.is_a?(String) - options.except(:exact_text).merge(text: text_pattern(text, exact: exact == true)) - else - options - end + return options if text.is_a?(Regexp) || !(text.is_a?(String) || exact.is_a?(String)) + + pattern = if exact.is_a?(String) + text_pattern(exact, exact: true, containing: text) + else + text_pattern(text, exact: exact == true) + end + options.except(:exact_text).merge(text: pattern) end - # A Regexp matching +text+ with any whitespace between its words, ignoring case. + # A Regexp matching +text+ with any whitespace between its words, ignoring + # case. With +containing+, the match must also contain that text. # @return [Regexp] - def text_pattern(text, exact: false) - words = text.to_s.split.map { |word| Regexp.escape(word) }.join("\\s+") - Regexp.new(exact ? "\\A\\s*#{words}\\s*\\z" : words, Regexp::IGNORECASE) + def text_pattern(text, exact: false, containing: nil) + words = word_pattern(text) + words = "\\A\\s*#{words}\\s*\\z" if exact + return Regexp.new(words, Regexp::IGNORECASE) unless containing + + Regexp.new("(?=.*?#{word_pattern(containing)})#{words}", Regexp::IGNORECASE | Regexp::MULTILINE) + end + + # The words of +text+, escaped and joined by `\\s+`. + # @return [String] + def word_pattern(text) + text.to_s.split.map { |word| Regexp.escape(word) }.join("\\s+") end # A date as the date inputs take it: "2026-01-31" for a Date or a Time, diff --git a/spec/active_admin_page_objects/batch_actions_spec.rb b/spec/active_admin_page_objects/batch_actions_spec.rb index 31b39b0..5820389 100644 --- a/spec/active_admin_page_objects/batch_actions_spec.rb +++ b/spec/active_admin_page_objects/batch_actions_spec.rb @@ -22,6 +22,15 @@ expect(index.flashes).to have_flash(:notice, "Flagged 2 customers") end + # The button toggles the menu: a second click would close it. + it "applies an action when the menu is already open" do + batch_actions.select_all + find(:active_admin, :batch_actions_button).click + expect(batch_actions).to have_selector(:active_admin, :batch_action_item, text: "Flag Selected") + batch_actions.apply("Flag Selected") + expect(index.flashes).to have_flash(:notice, "Flagged 3 customers") + end + it "applies an action after accepting its confirmation" do batch_actions.select_all batch_actions.apply(:archive) diff --git a/spec/active_admin_page_objects/table_spec.rb b/spec/active_admin_page_objects/table_spec.rb index d071668..3e009fb 100644 --- a/spec/active_admin_page_objects/table_spec.rb +++ b/spec/active_admin_page_objects/table_spec.rb @@ -135,10 +135,14 @@ def declared_table(&) expect(row).to have_cell(:category, text: "retail") expect(row).to have_cell(:category, text: "RET", exact_text: false) expect(row).to have_no_cell(:category, exact_text: "RET") + expect(row).to have_cell(:category, text: "ret", exact_text: "Retail") + expect(row.has_cell?(:category, text: "xyz", exact_text: "Retail", wait: 0)).to be(false) expect(row.has_no_cell?(:category, exact_text: "retail", wait: 0)).to be(false) expect(row.cell(:email)).to have_text(customer.email) expect(row.cell(:actions)).to have_link("Delete") expect(row).to have_cell(:actions, text: "edit") + expect(row.cell(:selectable)).to have_css("input[type=checkbox]") + expect(row).to have_cell(:selectable) end it "keeps rows in table order" do diff --git a/spec/active_admin_page_objects/text_spec.rb b/spec/active_admin_page_objects/text_spec.rb index 8f3a0e6..21c91fc 100644 --- a/spec/active_admin_page_objects/text_spec.rb +++ b/spec/active_admin_page_objects/text_spec.rb @@ -23,6 +23,13 @@ expect(ActiveAdminPageObjects.case_insensitive_text(count: 1)).to eq(count: 1) end + it "keeps both a String text and a String exact_text" do + both = ActiveAdminPageObjects.case_insensitive_text(text: "Ac", exact_text: "Acme")[:text] + expect([both.match?("ACME"), both.match?("Acorn")]).to eq([true, false]) + conflicting = ActiveAdminPageObjects.case_insensitive_text(text: "xyz", exact_text: "Acme")[:text] + expect(conflicting.match?("Acme")).to be(false) + end + it "squishes whitespace and keeps the case" do expect(ActiveAdminPageObjects.squish(" External\n ID ")).to eq("External ID") end From 06b7f8cf06516aa2ffa511755f4afa2c678a4590 Mon Sep 17 00:00:00 2001 From: Denis Talakevich Date: Wed, 2 Dec 2026 11:09:48 +0200 Subject: [PATCH 7/7] Require ActiveAdmin 4.0.0.beta23 or later The comments section needs the active-admin-comments-form id, which ActiveAdmin added in beta20, and the suite runs on beta23 only. Co-Authored-By: Clanker --- CHANGELOG.md | 2 +- README.md | 2 +- active_admin_page_objects.gemspec | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98f75a8..9c1b8e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,7 @@ - `Panel#links` lists the links of the body as `{ text:, href: }`, with the `href` attribute as the page wrote it. - `ActiveAdminPageObjects::RSpec::Matchers`, loaded with `require "active_admin_page_objects/rspec"`: the matcher names of capybara_active_admin 1.0.0, which call the predicate of a page object and that gem's matcher for anything else. - `MainMenu#labels(*parents)` lists the item labels at a menu level. `MainMenu#click(*labels)` opens each collapsed parent with its toggle button and clicks the item's link, as a user does; it sees visible items only, so a hidden submenu raises `Capybara::ElementNotFound`. `go` still visits the link's URL. -- Version 2.x: page objects for vanilla ActiveAdmin 4 only. The gem now depends on `activeadmin` (>= 4.0.0.beta1, < 5.0.0.a). Vanilla ActiveAdmin 3 moves to the 1.x line. +- Version 2.x: page objects for vanilla ActiveAdmin 4 only. The gem now depends on `activeadmin` (>= 4.0.0.beta23, < 5.0.0.a): the comments section needs the `active-admin-comments-form` id of beta20, and beta23 is the version the suite runs on. Vanilla ActiveAdmin 3 moves to the 1.x line. - SitePrism page and sections for vanilla ActiveAdmin 4: layout, breadcrumbs, action items, flashes, main menu, index table, attributes table, panel, filters (string, numeric, select, boolean, date range), scopes, pagination, batch actions and formtastic forms. - `ActiveAdminPageObjects.register_selectors(**map)` takes only the selector map. It can also replace a key ActiveAdmin 4 removed, such as `tabs`. - `ActiveAdminPageObjects::Layout.add_section` and `Layout.add_element` add a section or an element to every page that includes `Layout`, including page classes defined earlier. diff --git a/README.md b/README.md index d39ce32..60f0f90 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ end require "active_admin_page_objects" ``` -Runtime dependencies: `activeadmin` (>= 4.0.0.beta1, < 5.0.0.a), `site_prism` (>= 5.0, < 7) and `capybara` (>= 3.37), on Ruby 3.3 or later. +Runtime dependencies: `activeadmin` (>= 4.0.0.beta23, < 5.0.0.a), `site_prism` (>= 5.0, < 7) and `capybara` (>= 3.37), on Ruby 3.3 or later. ### Rails 8 setup diff --git a/active_admin_page_objects.gemspec b/active_admin_page_objects.gemspec index efc953c..254b1df 100644 --- a/active_admin_page_objects.gemspec +++ b/active_admin_page_objects.gemspec @@ -24,7 +24,7 @@ Gem::Specification.new do |spec| spec.files = Dir["lib/**/*.rb", "README.md", "CHANGELOG.md", "LICENSE"] spec.require_paths = ["lib"] - spec.add_dependency "activeadmin", ">= 4.0.0.beta1", "< 5.0.0.a" + spec.add_dependency "activeadmin", ">= 4.0.0.beta23", "< 5.0.0.a" spec.add_dependency "capybara", ">= 3.37" spec.add_dependency "site_prism", ">= 5.0", "< 7" end