diff --git a/CHANGELOG.md b/CHANGELOG.md index 72fedb1..0310fed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 1.2.0 (2026-12-02) + +### Added + +- `Filters` returns a `CheckBoxesFilter` for a check_boxes filter (`filter :tier, as: :check_boxes`): `set`, `check`, `uncheck`, `options`, `checked`, and `have_checked`. +- `Scopes#href(label)` and `#hrefs`. +- `MainMenu#has_submenu?(*labels)` and `#has_no_submenu?`: whether an item is a parent. A parent links to "#", so `href:` cannot tell it apart. +- `HasMany#fieldset(label:)`, `#has_fieldset?(label:)` and `#has_no_fieldset?(label:)` find a fieldset by the label of one of its own fields, ignoring case and formtastic's required marker. A nested has_many's labels do not count. This fits a has_many that labels each record's input with the record's name. +- `have_action_item` and `have_no_action_item` on a page: `has_no_action_item?` passes on a page without the action items container, where `action_items.has_no_item?` raises. +- `Form.object_name "name"` sets the prefix of the field names and ids, for a form named after another object. +- `BatchActions#click(label)` clicks an action and waits for no dialog, for an app that refuses the selection, such as with an error flash. +- `Tabs#body(label)` reads a tab's body by label, which also works under `rack_test`, where `current` is nil. +- `ModalDialog#has_field?` and `#has_no_field?` take the filters of Capybara's `:field` selector, such as `with:`, `type:`, `disabled:` and `placeholder:`. + +### Fixed + +- `Comments#add` checks for the new comment in the reloaded page. With `Capybara.automatic_reload` off, it raised `ObsoleteNode` on the panel found before the submit. +- `Form::Field#required?` is also true when the label holds `` and the wrapper is `optional`. +- The form's field prefix skips a control without a key in brackets, such as a hidden `collection_selection[]` before the fields of a custom batch action form. +- A Symbol field key keeps a leading underscore, as formtastic ids it: `field(:_memo)` finds `#customer__memo_input`. Column, row and filter keys still drop it, as ActiveAdmin's `col-` and `row-` classes do. + ## 1.1.0 (2026-12-01) ### Added diff --git a/README.md b/README.md index b31d078..89f74a9 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,11 @@ page_object.action_items.click("New Customer") expect(page_object.action_items).to have_item("More") ``` -ActiveAdmin 3 always renders the container, so assert on its items, not on the section. +ActiveAdmin 3 renders the container in its title bar, so assert on its items, not on the section. A custom page without the title bar has no container: `action_items` raises there. The page's `have_action_item` and `have_no_action_item` treat a missing container as no items: + +```ruby +expect(page_object).to have_no_action_item("Edit Customer") # also passes without a title bar +``` A `dropdown_menu` is an item too. `dropdown(label)` returns a `DropdownMenu` (the only one when called without a label): @@ -150,6 +154,7 @@ page_object.main_menu.go("Catalog", "Orders") page_object.main_menu.click("Catalog", "Orders") expect(page_object.main_menu).to have_item("Catalog", "Categories") expect(page_object.main_menu).to have_item("Catalog", "Orders", href: "/admin/orders") +expect(page_object.main_menu).to have_submenu("Catalog") # a parent; its link is "#" page_object.main_menu.href("Catalog", "Orders") # => "http://127.0.0.1:3000/admin/orders" in a browser page_object.main_menu.current_labels # => ["Catalog", "Orders"] page_object.main_menu.labels("Catalog") # => ["Categories", "Orders"] @@ -289,7 +294,7 @@ comments.delete("Called back") # accepts the browser confirmation ### Filters -`filter(key)` returns the section typed by the filter input: `StringFilter`, `NumericFilter`, `SelectFilter`, `BooleanFilter` or `DateRangeFilter`. The key is the one given to `filter :key`; the section wraps `#q__input`. Filters that [declare their filters](#declared-labels) take the declared name. A filter whose key holds its predicate, such as `filter :uuid_eq`, has a bare input and no predicate select: `fill_in(with:)` and `have_value` work, and a `predicate:` raises. +`filter(key)` returns the section typed by the filter input: `StringFilter`, `NumericFilter`, `SelectFilter`, `BooleanFilter`, `DateRangeFilter` or `CheckBoxesFilter`. The key is the one given to `filter :key`; the section wraps `#q__input`. Filters that [declare their filters](#declared-labels) take the declared name. A filter whose key holds its predicate, such as `filter :uuid_eq`, has a bare input and no predicate select: `fill_in(with:)` and `have_value` work, and a `predicate:` raises. ```ruby filters = index.filters @@ -298,6 +303,7 @@ filters.filter(:balance).fill_in(with: 100, predicate: :gt) filters.filter(:status).select_option("Active") filters.filter(:active).set(true) # false, or nil for "Any" filters.filter(:created_at).set("2026-01-01", Date.new(2026, 1, 31)) +filters.filter(:tier).set(%w[Gold Silver]) # check_boxes: ticks these, unticks the rest filters.submit filters.clear # needs a JavaScript driver @@ -305,6 +311,7 @@ expect(filters.filter(:name)).to have_value("Acme", predicate: "Equals") expect(filters.filter(:status)).to have_selected("Active") expect(filters.filter(:active)).to have_value(true) expect(filters.filter(:created_at)).to have_range("2026-01-01", "2026-01-31") +expect(filters.filter(:tier)).to have_checked("Gold", "Silver") ``` `DateRangeFilter` types the dates into the two inputs. It does not use the jQuery UI datepicker: it closes the picker through jQuery UI and waits until it is hidden, so the picker never covers the **Filter** button. `set` takes Date objects or ISO strings; `nil` or `""` clears that end. @@ -335,6 +342,8 @@ index.scopes.labels # => ["All", "Active"] index.scopes.select("Active") expect(index.scopes).to have_selected("Active") index.scopes.count("Active") # => 12, or nil without a count +index.scopes.href("Active") # => "/admin/customers?scope=active" +index.scopes.hrefs # => {"All" => "/admin/customers?scope=all", "Active" => "..."} ``` ### Pagination @@ -375,8 +384,12 @@ index.batch_actions.apply(:destroy) index.batch_actions.apply("Set Status Selected", status: "pending") expect(index.batch_actions).to have_action("Flag Selected") dialog = index.batch_actions.open_dialog("Set Status Selected") # unconfirmed: see Modal dialog +index.batch_actions.click("Merge Selected") # waits for nothing +expect(index.flashes).to have_flash(:error, "Select at least two customers to merge") ``` +`apply` and `open_dialog` wait for the dialog of an action with `confirm:` or `form:`. When the app may refuse the selection and show an error instead, use `click(label)`: it clicks the action and waits for no dialog. + ### Modal dialog `page.modal_dialog` is the dialog ActiveAdmin opens for batch actions. Use it to drive the dialog yourself, for example to cancel: @@ -386,6 +399,7 @@ dialog = index.modal_dialog dialog.title # => "Are you sure you want to do this?" dialog.fill("status", with: "pending") # input, select or datepicker, by field name expect(dialog).to have_field("status") +expect(dialog).to have_field("status", with: "pending", disabled: false) # filters of Capybara's :field dialog.confirm # or dialog.cancel expect(index).to have_no_modal_dialog ``` @@ -403,7 +417,7 @@ form.fill(name: "Acme", category: "Retail", active: false) # in this order form.submit ``` -`field(name)` returns the section typed by the formtastic input class. `fill(value)` sets the field the way its type needs. +`field(name)` returns the section typed by the formtastic input class. `fill(value)` sets the field the way its type needs. A Symbol name stays as it is, so `field(:_memo)` finds `#customer__memo_input`. The field ids and names start with the form's object name, which the gem reads from the first control named like `customer[name]`. When a form names its fields otherwise, set it on the form class: `object_name "batch_action_form_inputs"`. - `Form::StringField` for `string`, `email`, `url`, `phone`, `password`, `number` and `text`: `fill` types the value. `value`. - `Form::SelectField` for `select`: `fill` picks the option with that label. `options` (without the blank option) and `selected`. The `` of a JavaScript select widget. + # The first name with a key in brackets, such as `customer[name]`. A + # `collection_selection[]` before the fields has none. def first_control_name - find("input[name*='['], select[name*='['], textarea[name*='[']", match: :first, visible: :all)[:name] + root_element.synchronize do + controls = all("input[name*='['], select[name*='['], textarea[name*='[']", visible: :all, wait: false) + controls.map { |control| control[:name] }.find { |name| name.match?(/\A[^\[]+\[[^\]]+\]/) } || + raise(Capybara::ElementNotFound, "no named control in the form") + end end # The attribute of the field +name+, checked against the declarations when fields are declared. @@ -133,7 +144,7 @@ def field_key(name) declaration = declaration_for(name) raise ArgumentError, "#{name.inspect} is declared as a has_many, not as a field" if declaration&.fetch(:kind) == :has_many - slug(name) + field_slug(name) end # Checks the name before #field_prefix queries the page. diff --git a/lib/active_admin_page_objects/filters.rb b/lib/active_admin_page_objects/filters.rb index e159729..4ae1dac 100644 --- a/lib/active_admin_page_objects/filters.rb +++ b/lib/active_admin_page_objects/filters.rb @@ -37,7 +37,8 @@ def clear "numeric" => :NumericFilter, "select" => :SelectFilter, "boolean" => :BooleanFilter, - "date_range" => :DateRangeFilter + "date_range" => :DateRangeFilter, + "check_boxes" => :CheckBoxesFilter }.freeze private_constant :FILTER_CLASSES @@ -89,3 +90,4 @@ def page_element_keys(**visibility) require_relative "filters/select_filter" require_relative "filters/boolean_filter" require_relative "filters/date_range_filter" +require_relative "filters/check_boxes_filter" diff --git a/lib/active_admin_page_objects/filters/check_boxes_filter.rb b/lib/active_admin_page_objects/filters/check_boxes_filter.rb new file mode 100644 index 0000000..811112b --- /dev/null +++ b/lib/active_admin_page_objects/filters/check_boxes_filter.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +module ActiveAdminPageObjects + # A check_boxes filter (`filter :tier, as: :check_boxes`): one checkbox per + # choice, found by its label. + class CheckBoxesFilter < Filter + # Ticks the checkboxes labelled +labels+ and unticks the others. + def set(labels) + labels = Array(labels).map(&:to_s) + uncheck(*(checked - labels)) + check(*labels) + end + + # Ticks the checkboxes labelled +labels+. + def check(*labels) + labels.each { |label| choice(label).set(true) } + end + + # Unticks the checkboxes labelled +labels+. + def uncheck(*labels) + labels.each { |label| choice(label).set(false) } + end + + # The choice labels, in page order. + # @return [Array] + def options + choices.map(&:first) + end + + # The labels of the ticked checkboxes. + # @return [Array] + def checked + choices.select { |_label, input| input.checked? }.map(&:first) + end + + # True when exactly +labels+ are ticked, in any order. No labels: none ticked. + def has_checked?(*labels, **options) + eventually(**options) { checked_labels_match?(labels) } + end + + # Waits until the ticked checkboxes are no longer exactly +labels+. + def has_no_checked?(*labels, **options) + eventually(**options) { !checked_labels_match?(labels) } + end + + private + + def choices + all(:active_admin, :filter_choice, wait: false).map do |label| + [label.text(:all).strip, label.find("input", visible: :all)] + end + end + + def choice(label) + choices.find { |text, _input| same_text?(text, label) }&.last || + raise(Capybara::ElementNotFound, "no choice #{label.inspect} in #{options.inspect}") + end + + def checked_labels_match?(labels) + checked.map { |label| normalize_text(label) }.sort == labels.map { |label| normalize_text(label) }.sort + end + end +end diff --git a/lib/active_admin_page_objects/form.rb b/lib/active_admin_page_objects/form.rb index 5af1f87..2b6206d 100644 --- a/lib/active_admin_page_objects/form.rb +++ b/lib/active_admin_page_objects/form.rb @@ -20,6 +20,15 @@ class Form < Section selector_key :form class << self + # The form's object name, the prefix of its field names and ids, when the + # first named control does not tell it: `object_name "batch_action_form_inputs"`. + # Without an argument, returns it (nil when not set). + def object_name(name = nil) + return @object_name || (superclass.object_name if superclass.respond_to?(:object_name)) if name.nil? + + @object_name = name.to_s + end + # 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 @@ -64,8 +73,11 @@ def choose(option) end # True when formtastic marks the field required. Does not wait. + # True when formtastic marks the wrapper `required`, or the label holds + # the required marker, ``, as a hand-made label can. def required? - root_element[:class].to_s.split.include?("required") + root_element[:class].to_s.split.include?("required") || + root_element.has_css?(sel(:form_required_marker), wait: false, visible: :all) end # The field's first control: its input, select or textarea. @@ -128,8 +140,7 @@ def submit # @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) + declaration = Declarations.lookup(declared_has_many, association, declaration_key(association)) visibility = Declarations.visibility(declaration, visible) return HasMany.new(self, find(:css, sel(:has_many, association.to_s), **visibility)) unless declaration @@ -189,8 +200,12 @@ def semantic_error_expectation(messages) # Formtastic ids inputs `__input`; the object name # is the prefix of the first namespaced field name. + def declared_has_many + self.class.declarations.select { |_name, declaration| declaration[:kind] == :has_many } + end + def field_prefix - first_control_name[/\A[^\[]+/] + self.class.object_name || first_control_name[/\A[^\[]+/] end def exact_semantic_errors?(messages, strict_order) diff --git a/lib/active_admin_page_objects/has_many.rb b/lib/active_admin_page_objects/has_many.rb index 1b73a00..7a3e66a 100644 --- a/lib/active_admin_page_objects/has_many.rb +++ b/lib/active_admin_page_objects/has_many.rb @@ -86,10 +86,28 @@ 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. + # The fieldset at +index+ (0-based), or the one with a field labelled + # +label+, waiting for it to appear. A has_many that labels each record's + # input with the record's name is reached by that name: `fieldset(label: + # "Kyiv")`. The label is compared ignoring case and the required "*"; a + # Regexp matches part of it. + # @raise [ArgumentError] unless exactly one of +index+ and +label+ is given # @return [Fieldset] - def fieldset(index) - self.class.fieldset_class.new(self, all(:active_admin, :has_many_fieldset, minimum: index + 1)[index]) + def fieldset(index = nil, label: nil) + raise ArgumentError, "give a fieldset index or label:, not both" if index.nil? == label.nil? + + node = index ? all(:active_admin, :has_many_fieldset, minimum: index + 1)[index] : labelled_fieldset(label) + self.class.fieldset_class.new(self, node) + end + + # True when a fieldset has a field labelled +label+. + def has_fieldset?(label:, **options) + eventually(**options) { find_labelled_fieldset(label) } + end + + # Waits until no fieldset has a field labelled +label+. + def has_no_fieldset?(label:, **options) + eventually(**options) { find_labelled_fieldset(label).nil? } end # Clicks the add link, waits for the new fieldset and returns it. @@ -116,5 +134,33 @@ def has_fieldsets?(count: nil, **options) def has_no_fieldsets?(count: nil, **options) has_no_css?(sel(:has_many_fieldset), **given(count: count), **options) end + + private + + def labelled_fieldset(label) + root_element.synchronize do + find_labelled_fieldset(label) || + raise(Capybara::ElementNotFound, "no fieldset with a field labelled #{label.inspect}") + end + end + + # The container's own fieldsets, and their own field labels (a radio + # group's too), so a nested has_many or a check box choice never matches. + OWN_FIELDSETS_XPATH = "./fieldset[contains(concat(' ', normalize-space(@class), ' '), ' has_many_fields ')]" + OWN_LABELS_XPATH = "./ol/li/label | ./ol/li/fieldset/legend/label" + private_constant :OWN_FIELDSETS_XPATH, :OWN_LABELS_XPATH + + def find_labelled_fieldset(label) + all(:xpath, OWN_FIELDSETS_XPATH, wait: false).find do |node| + node.all(:xpath, OWN_LABELS_XPATH, wait: false).any? { |field_label| text_match?(label_text(field_label), label) } + end + end + + # The label text without formtastic's required marker, `*`. + def label_text(field_label) + text = squish(field_label.text) + marker = field_label.first(:css, sel(:form_required_marker_abbr), minimum: 0, wait: false) + marker ? text.delete_suffix(squish(marker.text)).strip : text + end end end diff --git a/lib/active_admin_page_objects/layout.rb b/lib/active_admin_page_objects/layout.rb index 997e9f3..159c957 100644 --- a/lib/active_admin_page_objects/layout.rb +++ b/lib/active_admin_page_objects/layout.rb @@ -84,5 +84,35 @@ def sidebar(title) def utility_navigation UtilityNavigation.new(self, find(:active_admin, :utility_navigation)) end + + # True when an action item labelled +label+ (case-insensitive) is shown. + # Unlike `action_items.has_item?`, a page without the action items + # container, such as a custom page without a title bar, has no item. + def has_action_item?(label, **options) + action_item_shown?(label, true, **options) + end + + # Waits until no action item labelled +label+ is shown. Passes on a page + # without the action items container. + def has_no_action_item?(label, **options) + action_item_shown?(label, false, **options) + end + + private + + def action_item_shown?(label, expected, wait: Capybara.default_max_wait_time) + page.document.synchronize(wait == false ? 0 : wait) do + action_item_labels.any? { |text| ActiveAdminPageObjects.same_text?(text, label) } == expected || + raise(Capybara::ExpectationNotMet) + end + true + rescue Capybara::ExpectationNotMet + false + end + + def action_item_labels + container = page.first(:active_admin, :action_items, minimum: 0, wait: false) + container ? ActionItems.new(self, container).labels : [] + end end end diff --git a/lib/active_admin_page_objects/main_menu.rb b/lib/active_admin_page_objects/main_menu.rb index 2c9583e..b6ee3a1 100644 --- a/lib/active_admin_page_objects/main_menu.rb +++ b/lib/active_admin_page_objects/main_menu.rb @@ -57,6 +57,18 @@ def has_no_item?(*labels, href: nil, **options) eventually(**options) { !item_with_href?(labels, href) } end + # True when the item at the label path +labels+ is a parent with a + # submenu, at any level: `has_submenu?("Settings", "Payments")`. A parent + # links to "#", so `href:` does not tell it apart. + def has_submenu?(*labels, **options) + eventually(**options) { submenu?(labels) } + end + + # Waits until the item at +labels+ is missing or has no submenu. + def has_no_submenu?(*labels, **options) + eventually(**options) { !submenu?(labels) } + end + # The labels of the top-level items, or of the submenu at the label path # +parents+, in menu order: `labels("Catalog") # => ["Categories", "Orders"]`. # @return [Array] @@ -75,6 +87,11 @@ def current_labels private + def submenu?(labels) + item = find_item(labels) + !item.nil? && children(item).any? + end + def item_with_href?(labels, expected) item = find_item(labels) return false if item.nil? diff --git a/lib/active_admin_page_objects/modal_dialog.rb b/lib/active_admin_page_objects/modal_dialog.rb index 8e3d5b7..3c8032c 100644 --- a/lib/active_admin_page_objects/modal_dialog.rb +++ b/lib/active_admin_page_objects/modal_dialog.rb @@ -41,18 +41,23 @@ def cancel wait_until_gone end - # True when the dialog form has a field named +name+. + # True when the dialog form has a field named +name+. Takes the filters of + # Capybara's `:field` selector: `with:`, `type:`, `disabled:`, `placeholder:`. def has_field?(name, **options) - has_css?("#{sel(:modal_dialog_form)} #{field_selector(name)}", **options) + dialog_form.has_selector?(:field, name: name.to_s, **options) end - # Waits until the dialog form has no field named +name+. + # Waits until the dialog form has no such field. def has_no_field?(name, **options) - has_no_css?("#{sel(:modal_dialog_form)} #{field_selector(name)}", **options) + dialog_form.has_no_selector?(:field, name: name.to_s, **options) end private + def dialog_form + find(:active_admin, :modal_dialog_form) + end + def field_selector(name) format('[name="%s"]', name) end diff --git a/lib/active_admin_page_objects/scopes.rb b/lib/active_admin_page_objects/scopes.rb index f00a9c4..e0467d2 100644 --- a/lib/active_admin_page_objects/scopes.rb +++ b/lib/active_admin_page_objects/scopes.rb @@ -34,6 +34,19 @@ def count(label) badge && Integer(badge.text[/\d+/]) end + # The `href` of the scope labelled +label+, as the page wrote it, such as + # "/admin/customers?scope=active". + # @return [String] + def href(label) + href_attribute(scope_link(label)) + end + + # Scope label => `href`, in page order. + # @return [Hash{String => String}] + def hrefs + all(:active_admin, :scope).to_h { |link| [label_of(link), href_attribute(link)] } + end + private def scope_link(label) diff --git a/lib/active_admin_page_objects/selectors.rb b/lib/active_admin_page_objects/selectors.rb index 24e675e..928df42 100644 --- a/lib/active_admin_page_objects/selectors.rb +++ b/lib/active_admin_page_objects/selectors.rb @@ -77,6 +77,7 @@ module Selectors filter_wrappers: ".filter_form_field", filter_predicate: "select", filter_value: "input", + filter_choice: "fieldset.choices > label", filter_range_from: 'input[name*="_gteq"]', filter_range_to: 'input[name*="_lteq"]', # jQuery UI renders one datepicker for the page, at the end of . @@ -114,6 +115,8 @@ module Selectors # Hidden inputs and the delete checkbox of a has_many fieldset are not fields. form_input_wrapper: "li.input:not(.hidden):not(.has_many_delete)", form_input: "li#%s_%s_input", + form_required_marker: "label abbr[title='required']", + form_required_marker_abbr: "abbr[title='required']", form_choice: "li.choice label", # The hidden input of a boolean or check_boxes wrapper is not a control. form_control: "input:not([type=hidden]), select, textarea", diff --git a/lib/active_admin_page_objects/tabs.rb b/lib/active_admin_page_objects/tabs.rb index 33f72c0..a5132fc 100644 --- a/lib/active_admin_page_objects/tabs.rb +++ b/lib/active_admin_page_objects/tabs.rb @@ -2,7 +2,8 @@ module ActiveAdminPageObjects # The `tabs` component. jQuery UI switches the tabs, so #current and #switch - # need a JavaScript driver; without one every tab body is shown. A tab is + # need a JavaScript driver; without one every tab body is shown, and + # `body(label)` reads a tab's body. A tab is # named by its whole label, ignoring case, or by a Regexp for a label with a # changing part: `switch(/\AOrders \(\d+\)\z/)`. class Tabs < Section @@ -22,14 +23,17 @@ def current # Opens the tab labelled +label+: a String (case-insensitive) or a Regexp. def switch(label) - link = find_link(label) || raise(Capybara::ElementNotFound, "no tab #{label.inspect} in #{labels.inspect}") - link.click + tab_link(label).click end - # The body of the open tab, or of the first tab when none is marked open. + # The body of the tab labelled +label+, or else of the open tab, or else of + # the first tab. A JavaScript driver shows the open tab's body only, so + # #switch to a tab before reading it there. + # @raise [Capybara::ElementNotFound] when there is no tab labelled +label+ # @return [Capybara::Node::Element] - def body - fragment = current_link && current_link[:href].to_s[/#(.+)\z/, 1] + def body(label = nil) + link = label.nil? ? current_link : tab_link(label) + fragment = link && link[:href].to_s[/#(.+)\z/, 1] fragment ? find(:id, fragment) : find(:active_admin, :tab_panel, match: :first) end @@ -53,6 +57,10 @@ def current_link first(:active_admin, :tab_current_link, minimum: 0, wait: false) end + def tab_link(label) + find_link(label) || raise(Capybara::ElementNotFound, "no tab #{label.inspect} in #{labels.inspect}") + end + def find_link(label) links.find { |link| text_match?(link.text, label) } end diff --git a/lib/active_admin_page_objects/text.rb b/lib/active_admin_page_objects/text.rb index efc52f8..7dac2ee 100644 --- a/lib/active_admin_page_objects/text.rb +++ b/lib/active_admin_page_objects/text.rb @@ -26,6 +26,15 @@ def text_match?(actual, expected) expected.is_a?(Regexp) ? expected.match?(squish(actual)) : same_text?(actual, expected) end + # The key formtastic writes into a field's id: a Symbol attribute such as + # `:_memo` as it is, since formtastic keeps the leading underscore that + # #slug strips; any other key as #slug gives it. + # @return [String] + def field_slug(key) + text = key.to_s + key.is_a?(Symbol) && text.match?(/\A[a-z0-9_]+\z/) ? text : slug(key) + 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/lib/active_admin_page_objects/version.rb b/lib/active_admin_page_objects/version.rb index dfa328d..a0cef33 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 = "1.1.0" + VERSION = "1.2.0" end diff --git a/spec/active_admin_page_objects/action_items_spec.rb b/spec/active_admin_page_objects/action_items_spec.rb index 90c7d99..0de5ba5 100644 --- a/spec/active_admin_page_objects/action_items_spec.rb +++ b/spec/active_admin_page_objects/action_items_spec.rb @@ -16,6 +16,14 @@ expect(index.action_items).to have_no_item("Delete Customer") end + it "checks for an item on the page, also without the action items container" do + expect(index).to have_action_item("report") + expect(index).to have_no_action_item("Delete Customer") + page.execute_script("document.getElementById('title_bar').remove()") + expect(index).to have_no_action_item("Report") + expect(index.has_action_item?("Report", wait: 0)).to be(false) + end + it "clicks an item" do index.action_items.click("New Customer") expect(Pages::CustomerForm.new).to have_page_title(text: "New Customer") diff --git a/spec/active_admin_page_objects/batch_actions_spec.rb b/spec/active_admin_page_objects/batch_actions_spec.rb index 3b6948a..1e31f87 100644 --- a/spec/active_admin_page_objects/batch_actions_spec.rb +++ b/spec/active_admin_page_objects/batch_actions_spec.rb @@ -61,6 +61,21 @@ expect { batch_actions.open_dialog("Flag Selected") }.to raise_error(ArgumentError, /opens no dialog/) end + it "clicks an action that the app refuses without its dialog" do + index.table.row(customers.first.id).select + expect(batch_actions.click("Merge Selected")).to be_nil + expect(index.flashes).to have_flash(:error, "Select at least two customers to merge") + expect(index).to have_no_modal_dialog + end + + it "clicks an action whose dialog opens" do + batch_actions.select_all + batch_actions.click(:merge) + expect(index).to have_modal_dialog + index.modal_dialog.confirm + expect(index.flashes).to have_flash(:notice, "Merged 3 customers") + end + it "applies the default destroy action" do index.table.row(customers.first.id).select batch_actions.apply("Delete Selected") diff --git a/spec/active_admin_page_objects/comments_spec.rb b/spec/active_admin_page_objects/comments_spec.rb index 91c52d4..8e6a3d7 100644 --- a/spec/active_admin_page_objects/comments_spec.rb +++ b/spec/active_admin_page_objects/comments_spec.rb @@ -36,6 +36,17 @@ def create_comment(body) expect(ActiveAdmin::Comment.pluck(:body)).to eq(["First comment"]) end + # Without automatic reload, the panel found before the submit goes stale + # when the page reloads, so #add must look in the new page. + it "adds a comment without Capybara's automatic reload" do + Capybara.automatic_reload = false + show.load(id: customer.id) + show.comments.add("First comment") + expect(show.comments).to have_comment("First comment") + ensure + Capybara.automatic_reload = true + end + it "reads existing comments" do create_comment("First comment") create_comment("Second comment") diff --git a/spec/active_admin_page_objects/filters_spec.rb b/spec/active_admin_page_objects/filters_spec.rb index 3c96823..5935700 100644 --- a/spec/active_admin_page_objects/filters_spec.rb +++ b/spec/active_admin_page_objects/filters_spec.rb @@ -481,6 +481,34 @@ def native_select_visibility = :all end end + describe ActiveAdminPageObjects::CheckBoxesFilter do + before do + Customer.find_by!(name: "Alpha").update!(tier: "Gold") + Customer.find_by!(name: "Beta").update!(tier: "Silver") + index.load(query: { with_tier_filter: 1 }) + end + + # The page object declares its filters; this one is only on the page with the query. + let(:lenient) { ActiveAdminPageObjects::Filters.new(index, filters.root_element) } + + it "ticks choices by label and filters by them" do + tier = lenient.filter(:tier) + expect(tier).to be_an_instance_of(described_class) + expect(tier.label.downcase).to eq("tier") + expect(tier.options).to eq(%w[Bronze Silver Gold]) + expect(tier).to have_checked + tier.set(%w[gold Silver]) + expect(tier.checked).to eq(%w[Silver Gold]) + expect(tier).to have_checked("Gold", "Silver") + expect(tier).to have_no_checked("Gold", wait: 0) + tier.uncheck("Silver") + filters.submit + expect(names).to eq(["Alpha"]) + expect(lenient.filter(:tier)).to have_checked("Gold") + expect { lenient.filter(:tier).check("Platinum") }.to raise_error(Capybara::ElementNotFound, /Platinum/) + end + end + describe ActiveAdminPageObjects::DateRangeFilter do it "sets a range from ISO strings and Date objects" do index.load diff --git a/spec/active_admin_page_objects/form_spec.rb b/spec/active_admin_page_objects/form_spec.rb index 9e42315..5aefc04 100644 --- a/spec/active_admin_page_objects/form_spec.rb +++ b/spec/active_admin_page_objects/form_spec.rb @@ -202,6 +202,15 @@ def declared_form(&) expect(mistyped).to have_declared_fields end + it "reaches a field whose attribute starts with an underscore" do + form_page.load(action: "new", query: { with_memo: 1 }) + lenient = described_class.new(form_page, form.root_element) + lenient.field(:_memo).fill("Call back") + expect(lenient.field(:_memo).value).to eq("Call back") + declared = Class.new(described_class) { field :_memo, "Memo", ActiveAdminPageObjects::Form::StringField } + expect(declared.new(form_page, form.root_element)).to have_declared_fields + end + it "takes any key without declarations" do form_page.load(action: "new") lenient = described_class.new(form_page, form.root_element) @@ -359,6 +368,43 @@ def declared_form(&) expect(form.field(:status).input.tag_name).to eq("select") end + it "tells a field required by its label's marker alone" do + refund = Class.new(ActiveAdminPageObjects::Page) do + set_url "/admin/orders/combined_refund" + section :form, ActiveAdminPageObjects::Form + end.new + refund.load + expect(refund.form.field(:note).root_element[:class]).to include("optional") + expect(refund.form.field(:note)).to be_required + end + + describe "a form named after another object" do + let(:refund) do + Class.new(ActiveAdminPageObjects::Page) do + set_url "/admin/orders/combined_refund{?query*}" + section :form, ActiveAdminPageObjects::Form + end.new + end + + before { refund.load(query: { ids: "11,12" }) } + + it "takes the prefix from the first name with a key, past collection_selection[]" do + expect(refund.form.field(:description)).to be_required + refund.form.field(:description).fill("Overcharge") + refund.form.submit + expect(Pages::OrderIndex.new.flashes).to have_flash(:notice, "Refund Overcharge for 2 orders") + end + + it "takes the object name the form class sets" do + named = Class.new(ActiveAdminPageObjects::Form) { object_name "batch_action_form_inputs" } + expect(named.object_name).to eq("batch_action_form_inputs") + expect(Class.new(named).object_name).to eq("batch_action_form_inputs") + expect(ActiveAdminPageObjects::Form.object_name).to be_nil + named.new(refund, refund.form.root_element).field(:note).fill("Late") + expect(refund.form.field(:note).value).to eq("Late") + end + end + it "sets a value past maxlength with JavaScript" do form_page.load(action: "new") form.fill(name: "Acme", email: "acme@example.com") diff --git a/spec/active_admin_page_objects/has_many_spec.rb b/spec/active_admin_page_objects/has_many_spec.rb index 70b96cb..481cc02 100644 --- a/spec/active_admin_page_objects/has_many_spec.rb +++ b/spec/active_admin_page_objects/has_many_spec.rb @@ -16,6 +16,42 @@ def declared_orders(&) form_class.new(form_page, form.root_element).has_many(:orders) end + describe "a fieldset by the label of one of its fields" do + before do + create_order("REF-1", "paid", 2) + create_order("REF-B1", "new", 1) + form_page.load(id: customer.id, action: "edit", query: { labelled_orders: 1 }) + end + + it "finds it ignoring case and the required marker" do + expect(orders.fieldset(label: "ref-b1").field(:reference).value).to eq("REF-B1") + expect(orders.fieldset(label: /\AREF-1\z/).field(:quantity).value).to eq("2") + expect(orders).to have_fieldset(label: "REF-1") + expect(orders).to have_no_fieldset(label: "REF-9") + expect(orders.has_fieldset?(label: "REF-9", wait: 0)).to be(false) + expect { orders.fieldset(label: "REF-9") }.to raise_error(Capybara::ElementNotFound, /REF-9/) + expect { orders.fieldset(0, label: "REF-1") }.to raise_error(ArgumentError) + expect { orders.fieldset }.to raise_error(ArgumentError) + end + + it "looks at the fieldset's own fields, not at a nested has_many" do + page.execute_script(<<~JS) + document.querySelector("fieldset.has_many_fields > ol").insertAdjacentHTML("beforeend", + '
    1. ' + + '
  • '); + JS + expect(orders.fieldset(label: "REF-B1").field(:reference).value).to eq("REF-B1") + end + + it "keeps a trailing * that is not the required marker" do + page.execute_script(<<~JS) + document.querySelectorAll("fieldset.has_many_fields")[1].querySelector("li.input:not(.hidden) label[for$='_quantity']").textContent = "Warehouse*"; + JS + expect(orders.fieldset(label: "Warehouse*").field(:reference).value).to eq("REF-B1") + expect(orders).to have_no_fieldset(label: "Warehouse") + end + end + shared_examples "saved fieldsets" do before do create_order("REF-1", "paid", 2) diff --git a/spec/active_admin_page_objects/main_menu_spec.rb b/spec/active_admin_page_objects/main_menu_spec.rb index 5c5303c..ede058d 100644 --- a/spec/active_admin_page_objects/main_menu_spec.rb +++ b/spec/active_admin_page_objects/main_menu_spec.rb @@ -28,6 +28,14 @@ expect { dashboard.main_menu.has_item? }.to raise_error(ArgumentError) end + it "checks for a parent with a submenu" do + expect(dashboard.main_menu).to have_submenu("Catalog") + expect(dashboard.main_menu).to have_no_submenu("Tags") + expect(dashboard.main_menu).to have_no_submenu("Catalog", "Orders") + expect(dashboard.main_menu).to have_no_submenu("Reports") + expect(dashboard.main_menu.has_submenu?("Tags", wait: 0)).to be(false) + end + it "lists item labels" do expect(dashboard.main_menu.labels).to eq(%w[Dashboard Customers Tags Catalog]) expect(dashboard.main_menu.labels("catalog")).to eq(%w[Categories Orders]) diff --git a/spec/active_admin_page_objects/modal_dialog_spec.rb b/spec/active_admin_page_objects/modal_dialog_spec.rb index 730f1df..833739a 100644 --- a/spec/active_admin_page_objects/modal_dialog_spec.rb +++ b/spec/active_admin_page_objects/modal_dialog_spec.rb @@ -21,7 +21,11 @@ def open_batch_action(label) expect(dialog.title).to eq("Are you sure you want to do this?") expect(dialog).to have_field("status") expect(dialog).to have_no_field("missing", wait: 0) + expect(dialog).to have_field("status", type: "select", disabled: false) + expect(dialog).to have_no_field("status", type: "textarea", wait: 0) dialog.fill("status", with: "pending") + expect(dialog).to have_field("status", with: "pending") + expect(dialog).to have_no_field("status", with: "closed", wait: 0) dialog.confirm expect(index.flashes).to have_flash(:notice, "Set pending on 3 customers") diff --git a/spec/active_admin_page_objects/scopes_spec.rb b/spec/active_admin_page_objects/scopes_spec.rb index 09b0f8e..896d874 100644 --- a/spec/active_admin_page_objects/scopes_spec.rb +++ b/spec/active_admin_page_objects/scopes_spec.rb @@ -16,6 +16,15 @@ expect(scopes.labels).to eq(%w[All Active Inactive]) end + it "reads the scope links" do + expect(scopes.href("active")).to eq("/admin/customers?scope=active") + expect(scopes.hrefs).to eq( + "All" => "/admin/customers?scope=all", + "Active" => "/admin/customers?scope=active", + "Inactive" => "/admin/customers?scope=inactive" + ) + end + it "reads the counts" do expect(scopes.count("All")).to eq(3) expect(scopes.count("active")).to eq(2) diff --git a/spec/active_admin_page_objects/tabs_spec.rb b/spec/active_admin_page_objects/tabs_spec.rb index 88472ad..04d525c 100644 --- a/spec/active_admin_page_objects/tabs_spec.rb +++ b/spec/active_admin_page_objects/tabs_spec.rb @@ -25,6 +25,23 @@ expect(show.tabs.body).to have_no_text("Overview body") end + it "reads a tab's body by label" do + show.tabs.switch("Orders") + expect(show.tabs.body("orders")).to have_text("REF-1") + expect { show.tabs.body("Missing") }.to raise_error(Capybara::ElementNotFound, /Missing/) + end + + context "without JavaScript", driver: :rack_test do + it "lists the tabs and reads each body by label" do + expect(show.tabs.labels).to eq(%w[Overview Orders]) + expect(show.tabs).to have_tab("Orders") + expect(show.tabs.current).to be_nil + expect(show.tabs.body("Overview")).to have_text("Overview body") + expect(show.tabs.body("Overview")).to have_no_text("REF-1") + expect(show.tabs.body("Orders")).to have_text("REF-1") + end + end + it "raises for a missing tab" do expect { show.tabs.switch("Missing") }.to raise_error(Capybara::ElementNotFound, /Missing/) end diff --git a/spec/active_admin_page_objects/text_spec.rb b/spec/active_admin_page_objects/text_spec.rb index e0e55b9..b87dd0e 100644 --- a/spec/active_admin_page_objects/text_spec.rb +++ b/spec/active_admin_page_objects/text_spec.rb @@ -21,6 +21,13 @@ it "slugs keys the way ActiveAdmin writes the col- and row- classes" do expect(ActiveAdminPageObjects.slug("EXTERNAL ID")).to eq("external_id") expect(ActiveAdminPageObjects.slug(:external_id)).to eq("external_id") + expect(ActiveAdminPageObjects.slug(:_memo)).to eq("memo") + end + + it "keeps a Symbol field key as formtastic ids it" do + expect(ActiveAdminPageObjects.field_slug(:_memo)).to eq("_memo") + expect(ActiveAdminPageObjects.field_slug("_memo")).to eq("memo") + expect(ActiveAdminPageObjects.field_slug("Signed up")).to eq("signed_up") expect(ActiveAdminPageObjects.slug("Signed up")).to eq("signed_up") end @@ -59,6 +66,6 @@ end it "has a version" do - expect(ActiveAdminPageObjects::VERSION).to eq("1.1.0") + expect(ActiveAdminPageObjects::VERSION).to eq("1.2.0") end end diff --git a/spec/dummy/app/admin/customers.rb b/spec/dummy/app/admin/customers.rb index d6ebdde..a482c4a 100644 --- a/spec/dummy/app/admin/customers.rb +++ b/spec/dummy/app/admin/customers.rb @@ -21,6 +21,8 @@ filter :category filter :active filter :created_at + # `?with_tier_filter=1` adds a check_boxes filter. + filter :tier, as: :check_boxes, collection: Customer::TIERS, if: proc { params[:with_tier_filter] } batch_action :flag do |ids| redirect_to collection_path, notice: "Flagged #{ids.size} customers" @@ -30,6 +32,11 @@ redirect_to collection_path, notice: "Archived #{ids.size} customers" end + # The dummy JavaScript refuses it for fewer than two rows, without the dialog. + batch_action :merge, confirm: "Merge the selected customers?" do |ids| + redirect_to collection_path, notice: "Merged #{ids.size} customers" + end + batch_action :set_status, form: { status: Customer::STATUSES } do |ids, inputs| redirect_to collection_path, notice: "Set #{inputs['status']} on #{ids.size} customers" end @@ -135,13 +142,17 @@ f.input :channels, as: :check_boxes, collection: Customer::CHANNELS end f.input :signed_on, as: :datepicker + # `?with_memo=1` adds an attribute whose name starts with an underscore. + f.input :_memo, as: :string if params[:with_memo] end f.has_many :orders, heading: "Orders", allow_destroy: true do |o| # A check_boxes input first: its hidden input is named `...[tags][]`. o.input :tags, as: :check_boxes, collection: %w[Gift Rush] if f.object.external_id == "ORDER-TAGS" o.input :reference o.input :state, as: :select, collection: Order::STATES - o.input :quantity, input_html: { disabled: params[:lock_quantity].present? } + # `?labelled_orders=1` labels each quantity with its order's reference. + quantity_label = params[:labelled_orders] ? { label: o.object.reference.to_s, required: true } : {} + o.input :quantity, **quantity_label, input_html: { disabled: params[:lock_quantity].present? } end f.actions end diff --git a/spec/dummy/app/admin/orders.rb b/spec/dummy/app/admin/orders.rb index 04f32e7..0e9f3eb 100644 --- a/spec/dummy/app/admin/orders.rb +++ b/spec/dummy/app/admin/orders.rb @@ -8,6 +8,13 @@ filter :customer filter :state, as: :select, collection: Order::STATES + collection_action :combined_refund, method: %i[get post] do + if request.post? + description = params.dig(:batch_action_form_inputs, :description) + redirect_to collection_path, notice: "Refund #{description} for #{params[:collection_selection]&.size.to_i} orders" + end + end + index do id_column column :reference diff --git a/spec/dummy/app/assets/javascripts/active_admin.js b/spec/dummy/app/assets/javascripts/active_admin.js index d2b66c5..24f154f 100644 --- a/spec/dummy/app/assets/javascripts/active_admin.js +++ b/spec/dummy/app/assets/javascripts/active_admin.js @@ -1 +1,16 @@ //= require active_admin/base + +// An app may check the selection before ActiveAdmin opens a batch dialog: this +// refuses "Merge Selected" for fewer than two rows with an error flash. The +// capture-phase listener runs before ActiveAdmin's handler. +document.addEventListener("click", function (event) { + var item = event.target.closest('a.batch_action[data-action="merge"]'); + if (!item || document.querySelectorAll("input.collection_selection:checked").length >= 2) return; + + event.preventDefault(); + event.stopImmediatePropagation(); + var flash = document.createElement("div"); + flash.className = "flash flash_error"; + flash.textContent = "Select at least two customers to merge"; + document.querySelector(".flashes").appendChild(flash); +}, true); diff --git a/spec/dummy/app/models/customer.rb b/spec/dummy/app/models/customer.rb index 23eb513..62cacf1 100644 --- a/spec/dummy/app/models/customer.rb +++ b/spec/dummy/app/models/customer.rb @@ -11,13 +11,13 @@ class Customer < ActiveRecord::Base accepts_nested_attributes_for :orders, allow_destroy: true serialize :channels, type: Array, coder: JSON - attr_accessor :password + attr_accessor :password, :_memo validates :name, presence: true validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ } validate :base_rules - def self.ransackable_attributes(_auth = nil) = %w[id name email external_id status balance active category_id created_at] + def self.ransackable_attributes(_auth = nil) = %w[id name email external_id status balance active category_id created_at tier] def self.ransackable_associations(_auth = nil) = %w[category] # The check_boxes input also posts a blank value. diff --git a/spec/dummy/app/views/admin/orders/combined_refund.html.erb b/spec/dummy/app/views/admin/orders/combined_refund.html.erb new file mode 100644 index 0000000..cf3d346 --- /dev/null +++ b/spec/dummy/app/views/admin/orders/combined_refund.html.erb @@ -0,0 +1,17 @@ +<%# A custom batch action page: the field prefix is not the resource's, and a hidden + `collection_selection[]` comes before the fields. %> +<%= semantic_form_for :batch_action_form_inputs, url: combined_refund_admin_orders_path, + html: { id: "combined_refund_batch_action", class: "batch-action-page-form" } do |f| %> + <%= hidden_field_tag "batch_action", "combined_refund" %> + <% params[:ids].to_s.split(",").each do |id| %> + <%= hidden_field_tag "collection_selection[]", id, id: nil %> + <% end %> + <%= f.inputs "New Combined Refund" do %> + <%= f.input :description, as: :string, required: true %> + <%# Marked required by the label alone: formtastic gives the wrapper the "optional" class. %> + <%= f.input :note, as: :string, required: false, label: safe_join(["Note", content_tag(:abbr, "*", title: "required")]) %> + <% end %> + <%= f.actions do %> + <%= f.action :submit, label: "Create Refund" %> + <% end %> +<% end %>