Skip to main content

Testing Your App

One spec checks every cm_admin block in your app and opens every admin page. cm-admin's own suite already tests the engine, so you only test your model definitions and the code your app owns.

1. Set up​

Add one line to spec/rails_helper.rb, after require "rspec/rails":

# spec/rails_helper.rb
require "cm_admin/testing/rspec"

That is the whole setup. Every request spec now has the cm-admin helpers and matchers: a spec under spec/requests/ (when you use infer_spec_type_from_file_location!) or one tagged type: :request.

Put the line in rails_helper.rb, not in a spec file. The helpers only reach specs that are loaded after it, and cm-admin warns if it is loaded too late.

2. Add the spec​

# spec/requests/cm_admin_spec.rb
require "rails_helper"

RSpec.describe "cm-admin", type: :request do
it_behaves_like "valid cm_admin model definitions"
it_behaves_like "cm_admin pages render"
end
  • valid cm_admin model definitions checks that every attribute, association, helper, partial and scope a cm_admin block names exists, and calls each filter_with scope to check its arguments.
  • cm_admin pages render signs in a full-access user and opens every page a model declares (see the table below). It also fails on fields that show ERR: Contact Support, which still return 200.
Declared in the cm_admin blockWhat is openedExample id
Default actions and tabsindex, new, show, edit, history, each tabInvoice#show
custom_action with display_type: :page/:form_pageThe page (GET actions only)Invoice#preview
custom_action with display_type: :modal/:form_modalThe modal content, without submitting itInvoice#approve
cm_dashboardThe dashboard and each widgetInvoice#dashboard/revenue_1a2b3c4d
importableThe import formInvoice#import

It needs rspec-rails, factory_bot_rails, and a user and cm_role factory.

3. Add a factory per model​

Name each factory after its model, and make FactoryBot.create(:invoice) work with no arguments. Put whatever a model needs to be created in its factory, not in the spec. A model with no factory shows as pending.

4. Run it in CI​

bundle exec rspec runs both checks. bin/rails cm_admin:verify checks the model definitions alone, without factories.

Options​

OptionExample
Accept a reported problemignore: [/\AInvoice action :index/]
Don't call filter scopesprobe: false
Don't open some models or pagesskip: ["Invoice", "Payment#edit", /dashboard/]
Open only some models or pagesonly: ["Invoice", "Payment#show"]
Change the user or recordDefine cm_admin_user or cm_admin_record_for(cm_model) above it_behaves_like

skip and only take model names, page ids and regular expressions. Naming a dashboard also covers its widgets.

Spec helpers​

In any request spec you pass names from the cm_admin block; the helpers work out paths and permissions.

require "rails_helper"

RSpec.describe "Invoice admin", type: :request do
let(:invoice) { create(:invoice) }

it "lets an accountant view but not edit" do
cm_admin_sign_in(role: cm_admin_role(Invoice => %i[index show]))

get cm_admin_path(Invoice, :show, invoice)
expect(response).to have_http_status(:ok)

get cm_admin_path(Invoice, :edit, invoice)
expect(response).to redirect_to("/cm_admin/access-denied")
end
end
HelperWhat it does
cm_admin_sign_inSigns in a new user whose role has every permission the permissions screen could grant, on every action of every model, with the all scope. display_if conditions and override_policy policies still apply. Pass role: to sign in a restricted user instead. Returns the user.
cm_admin_sign_in(role: role)Signs in a new user with that role.
cm_admin_sign_in(user)Signs in a user you built. Add role: to change their role first.
cm_admin_role(Invoice => %i[index show])Builds a CmRole with those actions. :new also grants create, and :edit also grants update.
cm_admin_role(Invoice => {index: :own})Grants an action within a policy_scopes scope.
cm_admin_role(Invoice => :all)Grants every action of the model. cm_admin_role alone builds a role with no permissions.
cm_admin_path(Invoice, :approve, invoice)The path of an action. Member actions need the record.

In every request spec, cm-admin also:

  • signs the user out after each example;
  • fails the example if cm-admin rescued and reported an error while it ran, such as a column that shows ERR: Contact Support. Such a page still returns 200, so nothing else would catch it.

An example that expects cm-admin to report an error opts out of that check, alone or as a group:

it "shows the error marker when a column fails", cm_admin_errors: :allow do
# ...
end

Only request specs are covered:

  • Controller specs are not supported. Convert them to request specs, which Rails and rspec-rails recommend anyway.
  • System specs are not covered yet.
  • To use the helpers in another kind of group, include CmAdmin::Testing::RequestHelpers in it.

The helpers are strict. An action or policy scope the model does not declare raises an ArgumentError that lists the declared names, so a typo cannot make a spec pass by testing nothing:

LeaveRequest has no cm_admin action :aprove. Declared: :approve, :cancel, :index, ...

A request that raises, such as a record outside the user's policy scope (a 404), signs the user out of the test session. The helpers sign in again before each request they make; after such a request, call cm_admin_sign_in(user) again before a plain get or post of your own.

New users are built with your user factory. Records are yours to build: the helpers never create them.

Index pages​

cm_admin_index opens a model's index as the signed-in user and returns what the table lists. Name filters and sort columns as the cm_admin block declares them; the helper encodes each value for its filter type.

it "lists the paid invoices of March, largest first" do
cm_admin_sign_in
small = create(:invoice, status: :paid, total: 100, issued_on: Date.new(2026, 3, 5))
large = create(:invoice, status: :paid, total: 900, issued_on: Date.new(2026, 3, 9))
create(:invoice, status: :draft, issued_on: Date.new(2026, 3, 7))

index = cm_admin_index(Invoice,
filters: {status: "paid", issued_on: Date.new(2026, 3, 1)..Date.new(2026, 3, 31)},
sort: {total: :desc})

expect(index).to list_records(large, small).in_order
expect(index).to have_column(:total).with_value(large, "β‚Ή900.00")
end
OptionExampleNotes
search:search: "acme"Needs a :search filter on the index.
filters:filters: {status: "paid", customer_id: customer}Select filters take a value, a record or an array; :date and :range take a range.
advanced:advanced: [{filter: :email, condition: :is_empty}]Conditions of the advanced filter. Optional value: and operator: :or.
sort:sort: {total: :desc}A column declared with sort column:, plus created_at and updated_at.
page:, per_page:page: 2, per_page: 10per_page must be one of the sizes the page offers.
default_filters:default_filters: falseSkips the filters' default_value. They apply otherwise, as they do for a user.
as:as: accountantSigns that user in first, to check what their policy scope lets them see.
MatcherPasses when
list_records(a, b)The page lists exactly these records. Add .in_order to check the order.
not_to list_records(a, b)None of these records is listed.
include_records(a, b)These records are among the listed ones. .in_order checks their relative order.
list_count(3)The page reports 3 records in total, across all pages.
have_column(:total)The column is shown.
have_column(:total).with_value(invoice, "900")The column shows that text for the record. A regular expression works too.
have_column(:notes).hiddenThe column is in the table but hidden by default (viewable: false).

Things to know:

  • Only the first page is seen. list_records compares against the rows of one page (20 by default). Filter down to the records under test, or pass page:.
  • Build the expected order with a query, such as Invoice.order(total: :desc).to_a, when rows can tie.
  • Date filters take dates. The page sends whole dates, so a Time raises. For a datetime column the end date means midnight at the start of that day, exactly as in the browser.
  • An undeclared filter, sort column or column name raises an ArgumentError listing the declared ones.
  • Table view only: card and kanban views are not read.

"cm_admin filters" runs every filter an index declares once, with a sample value, and fails on an error. It catches a filter_with scope that raises:

RSpec.describe "Invoice filters", type: :request do
it_behaves_like "cm_admin filters", Invoice
end

Custom and bulk actions​

cm_admin_run submits a custom action for a record and tells you how it went. A failing action still redirects with the error in a flash or a modal, so the helpers read the outcome from cm-admin itself, not from the response.

it "approves a pending invoice" do
cm_admin_sign_in
invoice = create(:invoice, status: :pending)

expect(invoice).to offer_action(:approve)
expect(cm_admin_run(invoice, :approve)).to succeed
expect(invoice.reload).to be_approved
end

it "refuses to approve without a reviewer" do
cm_admin_sign_in
invoice = create(:invoice, status: :pending, reviewer: nil)

expect(cm_admin_run(invoice, :approve)).to fail_with("Reviewer can't be blank")
end
HelperWhat it does
cm_admin_run(invoice, :approve)Submits the action with its declared verb and path. Pass the model for a collection action.
cm_admin_run(invoice, :reject, params: {reason: "Duplicate"})Sends the fields of a :form_modal or :form_page action, nested under the model's param key.
cm_admin_run_bulk(Invoice, :approve_all, [a, b])Submits a bulk action for those records. Takes params: for a form modal.
cm_admin_open(invoice, :reject)Opens the action's modal or form page without submitting. Returns its title, text and field_names.
MatcherPasses when
succeedThe action ran and no record failed.
fail_with("message")The action failed with that message. Part of the message or a regular expression works.
fail_for(record)A bulk action failed for that record. Add .with_message("...") to check its message.
expect(invoice).to offer_action(:approve)The index row or the show page offers the action: permission, policy scope and display_if combined.
expect(invoice).to offer_action(:approve).to(user)The same, as that user. This signs them in for the rest of the example.

Things to know:

  • cm_admin_run does not check display_if. It submits the request as a crafted request would. Use offer_action to assert when an action is shown.
  • Failure messages are the exception's message, or the returned record's errors.full_messages. A bulk action raising ActiveRecord::RecordInvalid reports "Validation failed: ...".
  • offer_action covers edit, destroy and member custom actions.
  • A param that is not a form_field of the action raises an ArgumentError, as do params for an action without a form.

Access​

"cm_admin access" states what a role may do with a model. It makes one request for every action the model declares and expects the listed ones to go through and every other one to be denied, so an action added later is covered without touching the spec.

RSpec.describe "Invoice access", type: :request do
context "as an accountant" do
it_behaves_like "cm_admin access", Invoice, allowed: %i[index show approve]
end

context "as a role from your seeds" do
it_behaves_like "cm_admin access", Invoice, allowed: %i[index show], role: -> { CmRole.find_by!(name: "Auditor") }
end
end
OptionExampleNotes
allowed:%i[index show], :all, []:new covers create and :edit covers update, as on the permissions page.
role:-> { create(:cm_role, :accountant) }The role under test. Without it the role is built from allowed:.
skip:skip: %i[sync_with_bank]Actions to leave out, for example one that calls an external service.

It needs a factory for the model (or cm_admin_record_for, as for the page checks) and builds the user with your user factory.

For single checks, and for policy scopes, use the matchers:

it "lets an employee see only their own requests" do
employee = create(:user, cm_role: cm_admin_role(LeaveRequest => {index: :user_only, show: :user_only}))
own = create(:leave_request, user: employee)
other = create(:leave_request)

expect(cm_admin_index(LeaveRequest, as: employee)).to list_records(own)
expect(employee).to be_allowed_to(:show, own)
expect(employee).not_to be_allowed_to(:show, other)
end
Matcher / helperWhat it tells you
expect(user).to be_allowed_to(:edit, invoice)The action's request went through for that user. Pass the model for a collection action.
expect(result).to be_deniedA helper result or a response was sent to the access-denied page.
cm_admin_access(invoice, :edit):allowed, :denied, :not_found (outside the policy scope) or :unauthenticated. Takes as:.

Things to know:

  • An allowed request really runs. Checking :destroy deletes the record, and an allowed custom action runs its block (with no form input). A denied request never reaches the action.
  • Built-in endpoints (export, mentions) are not checked.
  • An undeclared action in allowed: or skip: raises an ArgumentError.

Forms​

cm_admin_create and cm_admin_update submit the new and edit forms. Name attributes as the form_fields in cm_new and cm_edit; a form that fails validation is rendered again with a 200, so the result reads the errors the page shows.

it "creates an invoice with its lines" do
cm_admin_sign_in
customer = create(:customer)

result = cm_admin_create(Invoice, customer_id: customer.id, due_on: "2026-04-30",
invoice_lines: [{description: "Hosting", amount: 900}])

expect(result).to create_record(Invoice).with(customer: customer)
expect(result.record.invoice_lines.count).to eq(1)
end

it "needs a customer" do
cm_admin_sign_in

expect(cm_admin_create(Invoice, due_on: "2026-04-30")).to have_validation_error(:customer_id, "must exist")
end
HelperWhat it does
cm_admin_create(Invoice, attributes)Submits the new form. The result has the created record, error_messages and the response.
cm_admin_update(invoice, attributes)Submits the edit form. result.record is the reloaded record.
cm_admin_form(Invoice, :new)Opens the new form, to check which fields it renders.
cm_admin_form(invoice)Opens the record's edit form. Takes as: and query params:.
MatcherPasses when
create_record(Invoice)A record was created. Add .with(total: 900) to check its attributes.
succeedThe form was saved. Use it for updates.
have_validation_error(:email, "can't be blank")The form showed that error for the attribute. The message is optional.
have_form_field(:discount)The form renders the field as a visible input.
have_form_field(:discount).disabled / .hiddenThe field is rendered disabled, or as a hidden input.

Things to know:

  • Nested fields take the nested_form_field name and a list of rows: invoice_lines: [{description: "Hosting"}]. Pass id: to change a row and _destroy: "1" to remove one.
  • Attributes are strict. A name that is not a form_field of the form raises an ArgumentError, because the request would send a field the user cannot fill in. Forms that declare no fields, or declare them in dynamic_fields, accept any name.
  • A progressive form is submitted as its last step with all attributes at once. Moving between steps is not covered.
  • A belongs_to error such as "User must exist" is found under the form field's name, :user_id.

Show pages​

cm_admin_show opens a record's show page, or one of its tabs.

it "shows the payments of a paid invoice" do
cm_admin_sign_in
invoice = create(:invoice, :paid)

show = cm_admin_show(invoice)
expect(show).to have_field(:status).with_value("PAID")
expect(show).to have_tab(:payments)

expect(cm_admin_show(invoice, tab: :payments)).to list_records(invoice.payments)
end
MatcherPasses when
have_field(:status)The page shows the field. A field hidden by display_if does not match.
have_field(:status).with_value("PAID")The field shows that text, as rendered. A regular expression works too.
have_tab(:payments)The tab is shown for this record and user. The first tab is :show.
list_records, include_records, list_count, have_columnOn an association tab, the same matchers as for an index.

cm_admin_show(invoice, tab: :payments, as: accountant) opens the page as that user. An undeclared field, tab or column raises an ArgumentError.

Markup for your own selectors​

The helpers read these attributes, and your own specs or scripts can use them too:

AttributeWhereValue
data-ct-entity-idEach row of an index or association tableThe record's id
data-ct-field-nameEach table header and cell, each show page field, and the wrapper of each form field (nested form fields included)The name declared in the cm_admin block
data-ct-field-typeThe same elementsThe field_type of a column or show field (string when not given); the input_type of a form field
expect(page).to have_css("tr[data-ct-entity-id='#{invoice.id}'] td[data-ct-field-name='status']", text: "Paid")
expect(page).to have_css(".card-info[data-ct-field-name='status']", text: "Paid")
expect(page).to have_css("form [data-ct-field-name='discount'][data-ct-field-type='decimal']")

A show page also renders the forms of its modal actions, so scope a show page selector to .card-info.