repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/menu_steps.rb | features/step_definitions/menu_steps.rb | # frozen_string_literal: true
Then(/^I should see a menu item for "([^"]*)"$/) do |name|
expect(page).to have_css "#main-menu li a", text: name
end
Then(/^I should not see a menu item for "([^"]*)"$/) do |name|
expect(page).to have_no_css "#main-menu li a", text: name
end
Then(/^the "([^"]*)" menu item should be hidden$/) do |name|
expect(page).to have_css "#main-menu .hidden a", text: name
end
Then(/^I should see a menu parent for "([^"]*)"$/) do |name|
expect(page).to have_css "#main-menu li button", text: name
end
Then(/^I should see a nested menu item for "([^"]*)"$/) do |name|
expect(page).to have_css "#main-menu li li a", text: name
end
Then(/^the "([^"]*)" menu item should be selected$/) do |name|
expect(page).to have_css "#main-menu li a.selected", text: name
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/index_scope_steps.rb | features/step_definitions/index_scope_steps.rb | # frozen_string_literal: true
Then(/^I should( not)? see the scope "([^"]*)"( selected)?$/) do |negate, name, selected|
should = "I should#{' not' if negate}"
scope = ".scopes#{' .index-button-selected' if selected}"
step %{#{should} see "#{name}" within "#{scope}"}
end
Then(/^I should see the scope "([^"]*)" not selected$/) do |name|
step %{I should see the scope "#{name}"}
expect(page).to have_no_css ".scopes .index-button-selected", text: name
end
Then(/^I should see the scope "([^"]*)" with the count (\d+)$/) do |name, count|
expect(page).to have_css ".scopes a", text: name
expect(page).to have_css ".scopes-count", text: count
end
Then(/^I should see the scope with label "([^"]*)"$/) do |label|
expect(page).to have_link(label)
end
Then(/^I should see the scope "([^"]*)" with no count$/) do |name|
expect(page).to have_css ".scopes a", text: name
expect(page).to have_no_css ".scopes-count"
end
Then "I should see a group {string} with the scopes {string} and {string}" do |group, name1, name2|
group = group.tr(" ", "").underscore.downcase
expect(page).to have_css ".scopes [data-group='#{group}'] a", text: name1
expect(page).to have_css ".scopes [data-group='#{group}'] a", text: name2
end
Then "I should see a default group with a single scope {string}" do |name|
expect(page).to have_css ".scopes [data-group=default] a", text: name
end
Then "I should not see any scopes" do
expect(page).to have_no_css ".scopes a"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/action_link_steps.rb | features/step_definitions/action_link_steps.rb | # frozen_string_literal: true
Then(/^I should see a member link to "([^"]*)"$/) do |name|
expect(page).to have_css(".data-table-resource-actions > a", text: name)
end
Then(/^I should not see a member link to "([^"]*)"$/) do |name|
%{Then I should not see "#{name}" within ".data-table-resource-actions > a"}
end
Then(/^I should see the actions column with the class "([^"]*)" and the title "([^"]*)"$/) do |klass, title|
expect(page).to have_css "th#{'.' + klass}", text: title
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/comment_steps.rb | features/step_definitions/comment_steps.rb | # frozen_string_literal: true
Then(/^I should see a comment by "([^"]*)"$/) do |name|
step %{I should see "#{name}" within "[data-test-comment-container]"}
end
Then(/^I should( not)? be able to add a comment$/) do |negate|
should = negate ? :not_to : :to
expect(page).send should, have_button("Add Comment")
end
When(/^I add a comment "([^"]*)"$/) do |comment|
step %{I fill in "comment_body" with "#{comment}"}
step %{I press "Add Comment"}
end
Given(/^(a|\d+) comments added by admin with an email "([^"]+)"?$/) do |number, email|
number = number == "a" ? 1 : number.to_i
admin_user = ensure_user_created(email)
comment_text = "Comment %i"
number.times do |i|
ActiveAdmin::Comment.create!(
namespace: "admin",
body: comment_text % i,
resource_type: Post.to_s,
resource_id: Post.first.id,
author_type: admin_user.class.to_s,
author_id: admin_user.id)
end
end
Then(/^I should see (\d+) comments?$/) do |number|
expect(page).to have_css("[data-test-comment-container]", count: number.to_i)
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/site_title_steps.rb | features/step_definitions/site_title_steps.rb | # frozen_string_literal: true
Around "@site_title" do |scenario, block|
previous_site_title = ActiveAdmin.application.site_title
begin
block.call
ensure
ActiveAdmin.application.site_title = previous_site_title
end
end
Then(/^I should see the site title "([^"]*)"$/) do |title|
expect(page).to have_css "[data-test-site-title]", text: title
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/filesystem_steps.rb | features/step_definitions/filesystem_steps.rb | # frozen_string_literal: true
module ActiveAdminContentsRollback
def files
@files ||= {}
end
# Records the contents of a file the first time we are
# about to change it
def record(filename)
contents = File.read(filename) rescue nil
files[filename] = contents unless files.has_key? filename
end
# Rolls the recorded files back to their original states
def rollback!
files.each { |file, contents| rollback_file(file, contents) }
@files = {}
end
# If the file originally had content, override the stuff on disk.
# Else, remove the file and its parent folder structure until Rails.root OR other files exist.
def rollback_file(file, contents)
if contents.present?
File.open(file, "w") { |f| f << contents }
else
File.delete(file)
begin
dir = File.dirname(file)
until dir == Rails.root
Dir.rmdir(dir) # delete current folder
dir = dir.split("/")[0..-2].join("/") # select parent folder
end
rescue Errno::ENOTEMPTY # Directory not empty
end
end
end
end
World(ActiveAdminContentsRollback)
After "@changes-filesystem or @requires-reloading" do
rollback!
end
Given(/^"([^"]*)" contains:$/) do |filename, contents|
path = Rails.root + filename
FileUtils.mkdir_p File.dirname path
record path
File.open(path, "w+") { |f| f << contents }
end
Given(/^I add "([^"]*)" to the "([^"]*)" model$/) do |code, model_name|
path = Rails.root.join "app", "models", "#{model_name}.rb"
record path
str = File.read(path).gsub(/^(class .+)$/, "\\1\n #{code}\n")
File.open(path, "w+") { |f| f << str }
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/attribute_steps.rb | features/step_definitions/attribute_steps.rb | # frozen_string_literal: true
Then(/^I should( not)? see the attribute "([^"]*)" with "([^"]*)"$/) do |negate, title, value|
elems = all ".attributes-table th:contains('#{title}') ~ td:contains('#{value}')"
if negate
expect(elems.first).to eq(nil), "attribute missing"
else
expect(elems.first).to_not eq(nil), "attribute missing"
end
end
Then(/^I should see the attribute "([^"]*)" with a nicely formatted datetime$/) do |title|
text = first(".attributes-table th:contains('#{title}') ~ td").text
expect(text).to match(/\w+ \d{1,2}, \d{4} \d{2}:\d{2}/)
end
Then(/^I should not see the attribute "([^"]*)"$/) do |title|
expect(page).to have_no_css ".attributes-table th", text: title
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/breadcrumb_steps.rb | features/step_definitions/breadcrumb_steps.rb | # frozen_string_literal: true
Around "@breadcrumb" do |scenario, block|
previous_breadcrumb = ActiveAdmin.application.breadcrumb
begin
block.call
ensure
ActiveAdmin.application.breadcrumb = previous_breadcrumb
end
end
Then(/^I should see a link to "([^"]*)" in the breadcrumb$/) do |text|
expect(page).to have_css "nav[aria-label=breadcrumb] a", text: text
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/batch_action_steps.rb | features/step_definitions/batch_action_steps.rb | # frozen_string_literal: true
Then(/^I (should|should not) see the batch action :([^\s]*) "([^"]*)"$/) do |maybe, sym, title|
selector = "[data-batch-action-item]"
selector += "[href='#'][data-action='#{sym}']" if maybe == "should"
verb = maybe == "should" ? :to : :to_not
expect(page).send verb, have_css(selector, text: title)
end
Then(/^the (\d+)(?:st|nd|rd|th) batch action should be "([^"]*)"$/) do |index, title|
batch_action = page.all("[data-batch-action-item]")[index.to_i - 1]
expect(batch_action.text).to match title
end
When(/^I check the (\d+)(?:st|nd|rd|th) record$/) do |index|
page.all(".batch-actions-resource-selection")[index.to_i].set true
end
Then(/^I should see that the batch action button is disabled$/) do
expect(page).to have_css ".batch-actions-dropdown button[disabled]"
end
Then(/^I (should|should not) see the batch action (button|selector)$/) do |maybe, type|
selector = ".batch-actions-dropdown"
selector += " button" if maybe == "should" && type == "button"
verb = maybe == "should" ? :to : :to_not
expect(page).send verb, have_css(selector)
end
Then(/^I should see the batch action popover$/) do
expect(page).to have_css ".batch-actions-dropdown"
end
Given(/^I submit the batch action form with "([^"]*)"$/) do |action|
page.find_by_id('batch_action', visible: false).set action
form = page.find_by_id 'collection_selection'
params = page.all("#collection_selection input", visible: false).each_with_object({}) do |input, obj|
key = input["name"]
value = input["value"]
if key == "collection_selection[]"
(obj[key] ||= []).push value if input.checked?
else
obj[key] = value
end
end
page.driver.submit form["method"], form["action"], params
end
When(/^I click "(.*?)" and accept confirmation$/) do |link|
accept_confirm do
click_on(link)
end
end
Then(/^I should not see checkboxes in the table$/) do
expect(page).to have_no_css ".paginated-collection table input[type=checkbox]"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/filter_steps.rb | features/step_definitions/filter_steps.rb | # frozen_string_literal: true
Around "@filters" do |scenario, block|
previous_current_filters = ActiveAdmin.application.current_filters
begin
block.call
ensure
ActiveAdmin.application.current_filters = previous_current_filters
end
end
Then(/^I should see a select filter for "([^"]*)"$/) do |label|
expect(page).to have_css ".filters-form-field.select label", text: label
end
Then(/^I should see a string filter for "([^"]*)"$/) do |label|
expect(page).to have_css ".filters-form-field.string label", text: label
end
Then(/^I should see a date range filter for "([^"]*)"$/) do |label|
expect(page).to have_css ".filters-form-field.date_range label", text: label
end
Then(/^I should see a number filter for "([^"]*)"$/) do |label|
expect(page).to have_css ".filters-form-field.numeric label", text: label
end
Then(/^I should see the following filters:$/) do |table|
table.rows_hash.each do |label, type|
step %{I should see a #{type} filter for "#{label}"}
end
end
Given(/^I add parameter "([^"]*)" with value "([^"]*)" to the URL$/) do |key, value|
url = page.current_url
separator = url.include?("?") ? "&" : "?"
visit url + separator + key.to_s + "=" + value.to_s
end
Then(/^I should have parameter "([^"]*)" with value "([^"]*)"$/) do |key, value|
query = URI(page.current_url).query
params = Rack::Utils.parse_query query
expect(params[key]).to eq value
end
Then(/^I should see current filter "([^"]*)" equal to "([^"]*)" with label "([^"]*)"$/) do |name, value, label|
expect(page).to have_css ".active-filters [data-filter='#{name}'] span", text: label
expect(page).to have_css ".active-filters [data-filter='#{name}'] strong", text: value
end
Then(/^I should see current filter "([^"]*)" equal to "([^"]*)"$/) do |name, value|
expect(page).to have_css ".active-filters [data-filter='#{name}'] strong", text: value
end
Then(/^I should see link "([^"]*)" in current filters/) do |label|
expect(page).to have_css ".active-filters [data-filter] strong a", text: label
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/user_steps.rb | features/step_definitions/user_steps.rb | # frozen_string_literal: true
def ensure_user_created(email)
AdminUser.create_with(password: "password", password_confirmation: "password").find_or_create_by!(email: email)
end
Given(/^(?:I am logged|log) out$/) do
click_on "Sign out" if page.all(:css, "a", text: "Sign out").any?
end
Given(/^I am logged in$/) do
logout(:user)
login_as ensure_user_created "admin@example.com"
end
Given(/^I am logged in with capybara$/) do
ensure_user_created "admin@example.com"
step "log out"
visit new_admin_user_session_path
fill_in "Email", with: "admin@example.com"
fill_in "Password", with: "password"
click_on "Sign In"
end
Given(/^an admin user "([^"]*)" exists$/) do |email|
ensure_user_created(email)
end
Given(/^"([^"]*)" requests a password reset with token "([^"]*)"( but it expires)?$/) do |email, token, expired|
visit new_admin_user_password_path
fill_in "Email", with: email
allow(Devise).to receive(:friendly_token).and_return(token)
click_on "Reset My Password"
AdminUser.where(email: email).first.update_attribute :reset_password_sent_at, 1.month.ago if expired
end
Given(/^override locale "([^"]*)" with "([^"]*)"$/) do |path, value|
keys_value = path.split(".") + [value]
locale_hash = keys_value.reverse.inject { |a, n| { n => a } }
I18n.available_locales
I18n.backend.store_translations(I18n.locale, locale_hash)
end
When(/^I fill in the password field with "([^"]*)"$/) do |password|
fill_in "admin_user_password", with: password
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/rails_helper.rb | spec/rails_helper.rb | # frozen_string_literal: true
require "spec_helper"
ENV["RAILS_ENV"] = "test"
require_relative "../tasks/test_application"
require "#{ActiveAdmin::TestApplication.new.full_app_dir}/config/environment.rb"
require "rspec/rails"
# Disabling authentication in specs so that we don't have to worry about
# it allover the place
ActiveAdmin.application.authentication_method = false
ActiveAdmin.application.current_user_method = false
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.render_views = false
config.include Devise::Test::ControllerHelpers, type: :controller
require "support/active_admin_integration_spec_helper"
config.include ActiveAdminIntegrationSpecHelper
end
# Force deprecations to raise an exception.
ActiveAdmin::DeprecationHelper.behavior = :raise
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "simplecov" if ENV["COVERAGE"] == "true"
require_relative "support/matchers/perform_database_query_matcher"
require_relative "support/shared_contexts/capture_stderr"
require_relative "support/active_support_deprecation"
RSpec.configure do |config|
config.disable_monkey_patching!
config.filter_run focus: true
config.filter_run_excluding changes_filesystem: true
config.run_all_when_everything_filtered = true
config.color = true
config.order = :random
config.example_status_persistence_file_path = ".rspec_failures"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/tasks/gemfile_spec.rb | spec/tasks/gemfile_spec.rb | # frozen_string_literal: true
RSpec.describe "Gemfile sanity" do
it "is up to date" do
gemfile = ENV["BUNDLE_GEMFILE"] || "Gemfile"
current_lockfile = File.read("#{gemfile}.lock")
new_lockfile = Bundler.with_original_env do
`bundle lock --print`
end
msg = "Please update #{gemfile}'s lock file with `BUNDLE_GEMFILE=#{gemfile} bundle install` and commit the result"
expect(current_lockfile).to eq(new_lockfile), msg
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/tasks/local_spec.rb | spec/tasks/local_spec.rb | # frozen_string_literal: true
require "open3"
RSpec.describe "local task" do
let(:local) do
Open3.capture2e("bin/rake local runner 'AdminUser.first'")
end
it "succeeds" do
expect(local[1]).to be_success, local[0]
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/active_admin_integration_spec_helper.rb | spec/support/active_admin_integration_spec_helper.rb | # frozen_string_literal: true
module ActiveAdminIntegrationSpecHelper
def with_resources_during(example)
load_resources { yield }
example.run
load_resources {}
end
def reload_menus!
ActiveAdmin.application.namespaces.each { |n| n.reset_menu! }
end
# Sometimes we need to reload the routes within
# the application to test them out
def reload_routes!
Rails.application.reload_routes!
end
# Helper method to load resources and ensure that Active Admin is
# setup with the new configurations.
#
# Eg:
# load_resources do
# ActiveAdmin.register(Post)
# end
#
def load_resources
ActiveAdmin.unload!
yield
reload_menus!
reload_routes!
end
def arbre(assigns = {}, helpers = mock_action_view, &block)
Arbre::Context.new(assigns, helpers, &block)
end
def render_arbre_component(assigns = {}, helpers = mock_action_view, &block)
arbre(assigns, helpers, &block).children.first
end
# A mock action view to test view helpers
class MockActionView < ::ActionView::Base
include ActiveAdmin::LayoutHelper
include ActiveAdmin::AutoLinkHelper
include ActiveAdmin::DisplayHelper
include ActiveAdmin::IndexHelper
include MethodOrProcHelper
include Rails.application.routes.url_helpers
def compiled_method_container
self.class
end
end
# Returns a fake action view instance to use with our renderers
def mock_action_view(base = MockActionView)
controller = ActionView::TestCase::TestController.new
base.new(view_paths, {}, controller)
end
# Instantiates a fake decorated controller ready to unit test for a specific action
def controller_with_decorator(action, decorator_class)
method = action == "index" ? :apply_collection_decorator : :apply_decorator
controller_class = Class.new do
include ActiveAdmin::ResourceController::Decorators
public method
end
active_admin_config = double(decorator_class: decorator_class)
if action != "index"
form_presenter = double(options: { decorate: !decorator_class.nil? })
allow(active_admin_config).to receive(:get_page_presenter).with(:form).and_return(form_presenter)
end
controller = controller_class.new
allow(controller).to receive(:active_admin_config).and_return(active_admin_config)
allow(controller).to receive(:action_name).and_return(action)
controller
end
def view_paths
paths = ActionController::Base.view_paths
ActionView::LookupContext.new(paths)
end
def with_translation(scope, value)
previous_value = nil
previous_scope = scope.each_with_object([]) do |part, subscope|
subscope << part
previous_value = I18n.t(subscope.join("."), default: nil)
break subscope if previous_value.nil?
end
I18n.backend.store_translations I18n.locale, to_translation_hash(scope, value)
yield
ensure
I18n.backend.store_translations I18n.locale, to_translation_hash(previous_scope, previous_value)
end
def to_translation_hash(scope, value)
scope.reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/rails_template_with_data.rb | spec/support/rails_template_with_data.rb | # frozen_string_literal: true
apply File.expand_path("rails_template.rb", __dir__)
inject_into_file "config/initializers/active_admin.rb", <<-RUBY, after: "ActiveAdmin.setup do |config|"
config.comments_menu = { parent: 'Administrative' }
RUBY
inject_into_file "app/admin/admin_users.rb", <<-RUBY, after: "ActiveAdmin.register AdminUser do"
menu parent: "Administrative", priority: 1
RUBY
directory File.expand_path("templates_with_data/admin", __dir__), "app/admin"
append_file "db/seeds.rb", "\n\n" + <<~RUBY
texts = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Sed metus lacus, sagittis et feugiat a, vestibulum non risus.",
"Vestibulum eu eleifend orci, eget ornare velit.",
"Proin rhoncus velit imperdiet sapien iaculis tempor.",
"Morbi a semper justo.",
"Donec at sagittis nunc.",
"Proin vitae accumsan elit, ut tincidunt tellus.",
"Interdum et malesuada fames ac ante ipsum primis in faucibus.",
"Morbi suscipit ex quis est tincidunt ultrices. Integer blandit scelerisque nisi.",
"Aenean lacinia molestie maximus.",
"Mauris blandit sem nec nisl sollicitudin scelerisque.",
"Praesent ac nisi eu dui consectetur aliquet vitae ac ante.",
"Vivamus vel arcu eget lacus luctus tempus."
]
user_data = ["Jimi Hendrix", "Jimmy Page", "Yngwie Malmsteen", "Eric Clapton", "Kirk Hammett"].map do |name|
first, last = name.split(" ")
{
first_name: first,
last_name: last,
username: name.downcase.gsub(" ", ""),
age: rand(80),
encrypted_password: SecureRandom.hex
}
end
User.insert_all(user_data)
user_ids = User.pluck(:id)
category_data = ["Rock", "Pop Rock", "Alt-Country", "Blues", "Dub-Step"].map { |i| { name: i } }
Category.insert_all(category_data)
category_ids = Category.pluck(:id)
tag_data = ["Amy Winehouse", "Guitar", "Genius Oddities", "Music Culture"].map { |i| { name: i } }
Tag.insert_all(tag_data)
tag_ids = Tag.pluck(:id)
published_at_values = [5.days.ago, 1.day.ago, nil, 3.days.from_now]
post_data = Array.new(800) do |i|
user_id = user_ids[i % user_ids.size]
category_id = category_ids[i % category_ids.size]
published = published_at_values[i % published_at_values.size]
{
title: "Blog Post \#{i}",
body: texts.shuffle.slice(0, rand(1..texts.size)).join(" "),
custom_category_id: category_id,
published_date: published,
author_id: user_id,
starred: true
}
end
Post.insert_all(post_data)
post_ids = Post.pluck(:id)
tagging_data = post_ids.select { rand > 0.4 }.map do |id|
{
tag_id: tag_ids.sample,
post_id: id
}
end
Tagging.insert_all(tagging_data)
admin_user_id = AdminUser.first.id
comment_data = Array.new(800) do |i|
{
namespace: :admin,
author_type: "AdminUser",
author_id: admin_user_id,
body: texts.shuffle.slice(0, rand(1..texts.size)).join(" "),
resource_type: "Category",
resource_id: category_ids.sample
}
end
ActiveAdmin::Comment.insert_all(comment_data)
RUBY
rails_command "db:seed"
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/simplecov_regular_env.rb | spec/support/simplecov_regular_env.rb | # frozen_string_literal: true
if ENV["COVERAGE"] == "true"
require "simplecov"
SimpleCov.command_name ["regular specs", ENV["TEST_ENV_NUMBER"]].join(" ").rstrip
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/simplecov_changes_env.rb | spec/support/simplecov_changes_env.rb | # frozen_string_literal: true
if ENV["COVERAGE"] == "true"
require "simplecov"
SimpleCov.command_name "filesystem changes specs"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/rails_template.rb | spec/support/rails_template.rb | # frozen_string_literal: true
# Rails template to build the sample app for specs
gem "cssbundling-rails"
create_file "app/assets/config/manifest.js"
rails_command "css:install:tailwind"
# Remove default configuration generated: https://github.com/rails/cssbundling-rails/blob/v1.4.2/lib/install/tailwind/install.rb#L7
remove_file "app/assets/stylesheets/application.tailwind.css"
rails_command "importmap:install"
initial_timestamp = Time.now.strftime("%Y%m%d%H%M%S").to_i
template File.expand_path("templates/migrations/create_posts.tt", __dir__), "db/migrate/#{initial_timestamp}_create_posts.rb"
copy_file File.expand_path("templates/models/post.rb", __dir__), "app/models/post.rb"
copy_file File.expand_path("templates/post_decorator.rb", __dir__), "app/models/post_decorator.rb"
copy_file File.expand_path("templates/post_poro_decorator.rb", __dir__), "app/models/post_poro_decorator.rb"
template File.expand_path("templates/migrations/create_blog_posts.tt", __dir__), "db/migrate/#{initial_timestamp + 1}_create_blog_posts.rb"
copy_file File.expand_path("templates/models/blog/post.rb", __dir__), "app/models/blog/post.rb"
template File.expand_path("templates/migrations/create_profiles.tt", __dir__), "db/migrate/#{initial_timestamp + 2}_create_profiles.rb"
copy_file File.expand_path("templates/models/user.rb", __dir__), "app/models/user.rb"
template File.expand_path("templates/migrations/create_users.tt", __dir__), "db/migrate/#{initial_timestamp + 3}_create_users.rb"
copy_file File.expand_path("templates/models/profile.rb", __dir__), "app/models/profile.rb"
copy_file File.expand_path("templates/models/publisher.rb", __dir__), "app/models/publisher.rb"
template File.expand_path("templates/migrations/create_categories.tt", __dir__), "db/migrate/#{initial_timestamp + 4}_create_categories.rb"
copy_file File.expand_path("templates/models/category.rb", __dir__), "app/models/category.rb"
copy_file File.expand_path("templates/models/store.rb", __dir__), "app/models/store.rb"
template File.expand_path("templates/migrations/create_stores.tt", __dir__), "db/migrate/#{initial_timestamp + 5}_create_stores.rb"
template File.expand_path("templates/migrations/create_tags.tt", __dir__), "db/migrate/#{initial_timestamp + 6}_create_tags.rb"
copy_file File.expand_path("templates/models/tag.rb", __dir__), "app/models/tag.rb"
template File.expand_path("templates/migrations/create_taggings.tt", __dir__), "db/migrate/#{initial_timestamp + 7}_create_taggings.rb"
copy_file File.expand_path("templates/models/tagging.rb", __dir__), "app/models/tagging.rb"
copy_file File.expand_path("templates/helpers/time_helper.rb", __dir__), "app/helpers/time_helper.rb"
copy_file File.expand_path("templates/models/company.rb", __dir__), "app/models/company.rb"
template File.expand_path("templates/migrations/create_companies.tt", __dir__), "db/migrate/#{initial_timestamp + 8}_create_companies.rb"
template File.expand_path("templates/migrations/create_join_table_companies_stores.tt", __dir__), "db/migrate/#{initial_timestamp + 9}_create_join_table_companies_stores.rb"
inject_into_file "app/models/application_record.rb", before: "end" do
<<-RUBY
def self.ransackable_attributes(auth_object=nil)
authorizable_ransackable_attributes
end
def self.ransackable_associations(auth_object=nil)
authorizable_ransackable_associations
end
RUBY
end
environment 'config.hosts << ".ngrok-free.app"', env: :development
# Make sure we can turn on class reloading in feature specs.
# Write this rule in a way that works even when the file doesn't set `config.cache_classes` (e.g. Rails 7.1).
gsub_file "config/environments/test.rb", / config.cache_classes = true/, ""
inject_into_file "config/environments/test.rb", after: "Rails.application.configure do" do
"\n" + <<-RUBY
config.cache_classes = !ENV['CLASS_RELOADING']
RUBY
end
gsub_file "config/environments/test.rb", /config.enable_reloading = false/, "config.enable_reloading = !!ENV['CLASS_RELOADING']"
inject_into_file "config/environments/test.rb", after: "config.cache_classes = !ENV['CLASS_RELOADING']" do
"\n" + <<-RUBY
config.action_mailer.default_url_options = {host: 'example.com'}
config.active_record.maintain_test_schema = false
RUBY
end
gsub_file "config/boot.rb", /^.*BUNDLE_GEMFILE.*$/, <<-RUBY
ENV['BUNDLE_GEMFILE'] = "#{File.expand_path(ENV['BUNDLE_GEMFILE'])}"
RUBY
# In https://github.com/rails/rails/pull/46699, Rails 7.1 changed sqlite directory from db/ storage/.
# Since we test we deal with rails 6.1 and 7.0, let's go back to db/
gsub_file "config/database.yml", /storage\/(.+)\.sqlite3$/, 'db/\1.sqlite3'
# Setup Active Admin
generate "active_admin:install"
gsub_file "tailwind-active_admin.config.js", /^.*const activeAdminPath.*$/, <<~JS
const activeAdminPath = '../../../';
JS
gsub_file "tailwind-active_admin.config.js", Regexp.new("@activeadmin/activeadmin/plugin"), "../../../plugin"
# Force strong parameters to raise exceptions
inject_into_file "config/application.rb", after: "class Application < Rails::Application" do
"\n config.action_controller.action_on_unpermitted_parameters = :raise\n"
end
inject_into_file "package.json", after: '"private": "true",' do
"\n \"type\": \"module\",\n"
end
# Add some translations
append_file "config/locales/en.yml", File.read(File.expand_path("templates/en.yml", __dir__))
# Add predefined admin resources, override any file that was generated by rails new generator
directory File.expand_path("templates/admin", __dir__), "app/admin"
directory File.expand_path("templates/views", __dir__), "app/views"
directory File.expand_path("templates/policies", __dir__), "app/policies"
directory File.expand_path("templates/public", __dir__), "public", force: true
route "root to: redirect('admin')" if ENV["RAILS_ENV"] != "test"
# Rails 7.1 doesn't write test.sqlite3 files if we run db:drop, db:create and db:migrate in a single command.
# That's why we run it in two steps.
rails_command "db:drop db:create", env: ENV["RAILS_ENV"]
rails_command "db:migrate", env: ENV["RAILS_ENV"]
if ENV["RAILS_ENV"] == "test"
inject_into_file "config/database.yml", "<%= ENV['TEST_ENV_NUMBER'] %>", after: "test.sqlite3"
require "parallel_tests"
ParallelTests.determine_number_of_processes(nil).times do |n|
copy_file File.expand_path("db/test.sqlite3", destination_root), "db/test.sqlite3#{n + 1}"
# Copy Write-Ahead-Log (-wal) and Wal-Index (-shm) files.
# Files were introduced by rails 7.1 sqlite3 optimizations (https://github.com/rails/rails/pull/49349/files).
%w(shm wal).each do |suffix|
file = File.expand_path("db/test.sqlite3-#{suffix}", destination_root)
if File.exist?(file)
copy_file File.expand_path("db/test.sqlite3-#{suffix}", destination_root), "db/test.sqlite3#{n + 1}-#{suffix}", mode: :preserve
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/active_support_deprecation.rb | spec/support/active_support_deprecation.rb | # frozen_string_literal: true
# Module to help with deprecation warnings in specs.
module ActiveAdmin
# A good name for this module would be ActiveAdmin::ActiveSupport::Deprecation, but
# that would require a lot of changes in the codebase because, for example, there are references to
# ActiveSupport::Notification in ActiveAdmin module without the :: prefix.
# So, we are using ActiveAdmin::DeprecationHelper instead.
module DeprecationHelper
def self.behavior=(value)
if Rails.gem_version >= Gem::Version.new("7.1.0")
Rails.application.deprecators.behavior = :raise
else
ActiveSupport::Deprecation.behavior = :raise
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/shared_contexts/capture_stderr.rb | spec/support/shared_contexts/capture_stderr.rb | # frozen_string_literal: true
RSpec.shared_context "capture stderr" do
around do |example|
original_stderr = $stderr
$stderr = StringIO.new
example.run
$stderr = original_stderr
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/post_decorator.rb | spec/support/templates/post_decorator.rb | # frozen_string_literal: true
require "draper"
class PostDecorator < Draper::Decorator
decorates :post
delegate_all
# @param attributes [Hash]
def assign_attributes(attributes)
object.assign_attributes attributes.except(:virtual_title)
self.virtual_title = attributes.fetch(:virtual_title) if attributes.key?(:virtual_title)
end
def virtual_title
object.title
end
def virtual_title=(virtual_title)
object.title = virtual_title
end
def decorator_method
"A method only available on the decorator"
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/post_poro_decorator.rb | spec/support/templates/post_poro_decorator.rb | # frozen_string_literal: true
class PostPoroDecorator
delegate_missing_to :post
def initialize(post)
@post = post
end
def decorator_method
"A method only available on the PORO decorator"
end
private
attr_reader :post
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/helpers/time_helper.rb | spec/support/templates/helpers/time_helper.rb | # frozen_string_literal: true
module TimeHelper
def format_time(time, format: :long)
time
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/application_policy.rb | spec/support/templates/policies/application_policy.rb | # frozen_string_literal: true
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def index?
true
end
def show?
scope.where(id: record.id).exists?
end
def new?
create?
end
def create?
true
end
def edit?
update?
end
def update?
true
end
def destroy?
true
end
def destroy_all?
true
end
def scope
Pundit.policy_scope!(user, record.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/category_policy.rb | spec/support/templates/policies/category_policy.rb | # frozen_string_literal: true
class CategoryPolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/post_policy.rb | spec/support/templates/policies/post_policy.rb | # frozen_string_literal: true
class PostPolicy < ApplicationPolicy
def new?
true
end
def create?
record.category.nil? || record.category.name != "Announcements" || user.is_a?(User::VIP)
end
def update?
record.author == user
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/admin_user_policy.rb | spec/support/templates/policies/admin_user_policy.rb | # frozen_string_literal: true
class AdminUserPolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/user_policy.rb | spec/support/templates/policies/user_policy.rb | # frozen_string_literal: true
class UserPolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/store_policy.rb | spec/support/templates/policies/store_policy.rb | # frozen_string_literal: true
class StorePolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/company_policy.rb | spec/support/templates/policies/company_policy.rb | # frozen_string_literal: true
class CompanyPolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/tag_policy.rb | spec/support/templates/policies/tag_policy.rb | # frozen_string_literal: true
class TagPolicy < ApplicationPolicy
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/active_admin/page_policy.rb | spec/support/templates/policies/active_admin/page_policy.rb | # frozen_string_literal: true
module ActiveAdmin
class PagePolicy < ApplicationPolicy
def show?
case record.name
when "Dashboard"
true
else
false
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/policies/active_admin/comment_policy.rb | spec/support/templates/policies/active_admin/comment_policy.rb | # frozen_string_literal: true
module ActiveAdmin
class CommentPolicy < ApplicationPolicy
def destroy?
record.author == user
end
class Scope < ApplicationPolicy::Scope
def resolve
scope.where(author: user)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/admin/companies.rb | spec/support/templates/admin/companies.rb | # frozen_string_literal: true
ActiveAdmin.register Company do
permit_params :name, store_ids: []
form do |f|
f.inputs 'Company' do
f.input :name
f.input :stores
end
f.actions
end
show do
attributes_table :name, :stores, :created_at, :update_at
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/admin/stores.rb | spec/support/templates/admin/stores.rb | # frozen_string_literal: true
ActiveAdmin.register Store do
permit_params :name
index pagination_total: false
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/tag.rb | spec/support/templates/models/tag.rb | # frozen_string_literal: true
class Tag < ApplicationRecord
has_many :taggings
has_many :posts, through: :taggings
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/publisher.rb | spec/support/templates/models/publisher.rb | # frozen_string_literal: true
class Publisher < User
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/category.rb | spec/support/templates/models/category.rb | # frozen_string_literal: true
class Category < ApplicationRecord
has_many :posts, foreign_key: :custom_category_id
has_many :authors, through: :posts
accepts_nested_attributes_for :posts
validates :name, presence: true
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/store.rb | spec/support/templates/models/store.rb | # frozen_string_literal: true
class Store < ApplicationRecord
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/post.rb | spec/support/templates/models/post.rb | # frozen_string_literal: true
class Post < ApplicationRecord
belongs_to :category, foreign_key: :custom_category_id, optional: true, counter_cache: true
belongs_to :author, class_name: "User", optional: true
has_many :taggings
has_many :tags, through: :taggings
accepts_nested_attributes_for :author
accepts_nested_attributes_for :taggings, allow_destroy: true
# validates :title, :body, :author, :category, presence: true
ransacker :custom_title_searcher do |parent|
parent.table[:title]
end
ransacker :custom_created_at_searcher do |parent|
parent.table[:created_at]
end
ransacker :custom_searcher_numeric, type: :numeric do
# nothing to see here
end
class << self
def ransackable_scopes(_auth_object = nil)
super + [:fancy_filter]
end
def fancy_filter(value)
where(starred: value == "Starred")
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/profile.rb | spec/support/templates/models/profile.rb | # frozen_string_literal: true
class Profile < ApplicationRecord
belongs_to :user
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/tagging.rb | spec/support/templates/models/tagging.rb | # frozen_string_literal: true
class Tagging < ApplicationRecord
belongs_to :post, optional: true
belongs_to :tag, optional: true
delegate :name, to: :tag, prefix: true
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/company.rb | spec/support/templates/models/company.rb | # frozen_string_literal: true
class Company < ApplicationRecord
has_and_belongs_to_many :stores
validates :name, presence: true
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/user.rb | spec/support/templates/models/user.rb | # frozen_string_literal: true
class User < ApplicationRecord
class VIP < self
end
has_many :posts, foreign_key: "author_id"
has_many :articles, class_name: "Post", foreign_key: "author_id"
has_one :profile
accepts_nested_attributes_for :profile, allow_destroy: true
accepts_nested_attributes_for :posts, allow_destroy: true
ransacker :age_in_five_years, type: :numeric, formatter: proc { |v| v.to_i - 5 } do |parent|
parent.table[:age]
end
def display_name
"#{first_name} #{last_name}"
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates/models/blog/post.rb | spec/support/templates/models/blog/post.rb | # frozen_string_literal: true
class Blog::Post < ApplicationRecord
belongs_to :category, foreign_key: :custom_category_id
belongs_to :author, class_name: "User"
has_many :taggings
accepts_nested_attributes_for :author
accepts_nested_attributes_for :taggings, allow_destroy: true
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/matchers/perform_database_query_matcher.rb | spec/support/matchers/perform_database_query_matcher.rb | # frozen_string_literal: true
RSpec::Matchers.define :perform_database_query do |query|
match do |block|
query_regexp = query.is_a?(Regexp) ? query : Regexp.new(Regexp.escape(query))
@match = nil
callback = lambda do |_name, _started, _finished, _unique_id, payload|
if query_regexp.match?(payload[:sql])
@match = true
end
end
ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &block)
@match
end
failure_message do |_|
"Expected queries like \"#{query}\" but none were made"
end
failure_message_when_negated do |_|
"Expected no queries like \"#{query}\" but at least one were made"
end
supports_block_expectations
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/users.rb | spec/support/templates_with_data/admin/users.rb | # frozen_string_literal: true
ActiveAdmin.register User do
config.create_another = true
permit_params :first_name, :last_name, :username, :age
preserve_default_filters!
filter :first_name_or_last_name_cont, as: :string, label: "First or Last Name"
index do
selectable_column
id_column
column :first_name
column :last_name
column :username
column :age
column :created_at, class: "min-w-52"
column :updated_at, class: "min-w-52"
actions
end
index as: ActiveAdmin::Views::CustomIndex do |user|
label do
div class: "flex items-center gap-2 text-xl mb-2" do
resource_selection_cell user
span link_to(user.display_name, admin_user_path(user))
end
div "@#{user.username}", class: "mb-2"
div "#{user.age} years old", class: "mb-2 font-semibold"
end
end
show do
attributes_table_for(resource) do
row :id
row :first_name
row :last_name
row :username
row :age
row :created_at
row :updated_at
end
h3 "Posts", class: "font-bold py-5 text-2xl"
paginated_collection(user.posts.includes(:category).order(:updated_at).page(params[:page]).per(10), download_links: false) do
table_for(collection) do
column :id do |post|
link_to post.id, admin_user_post_path(post.author, post)
end
column :title
column :published_date
column :category
column :created_at
column :updated_at
end
end
div class: "mt-4" do
link_to "View all posts", admin_user_posts_path(user)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/posts.rb | spec/support/templates_with_data/admin/posts.rb | # frozen_string_literal: true
ActiveAdmin.register Post do
permit_params :custom_category_id, :author_id, :title, :body, :published_date, :position, :starred, taggings_attributes: [ :id, :tag_id, :name, :position, :_destroy ]
filter :author
filter :category, as: :check_boxes
filter :taggings
filter :tags, as: :check_boxes
filter :title
filter :body
filter :published_date
filter :position
filter :starred
filter :foo_id
filter :created_at
filter :updated_at
filter :custom_title_searcher
filter :custom_created_at_searcher
filter :custom_searcher_numeric
belongs_to :author, class_name: "User", param: "user_id", route_name: "user"
config.per_page = [ 5, 10, 20 ]
includes :author, :category, :taggings
scope :all, default: true
scope :drafts, group: :status do |posts|
posts.where(["published_date IS NULL"])
end
scope :scheduled, group: :status do |posts|
posts.where(["posts.published_date IS NOT NULL AND posts.published_date > ?", Time.current])
end
scope :published, group: :status do |posts|
posts.where(["posts.published_date IS NOT NULL AND posts.published_date < ?", Time.current])
end
scope :my_posts, group: :author do |posts|
posts.where(author_id: current_admin_user.id)
end
batch_action :set_starred, partial: "starred_batch_action_form", link_html_options: { "data-modal-target": "starred-batch-action-modal", "data-modal-show": "starred-batch-action-modal" } do |ids, inputs|
Post.where(id: ids).update_all(starred: inputs["starred"].present?)
redirect_to collection_path(user_id: params["user_id"]), notice: "The posts have been updated."
end
index do
selectable_column
id_column
column :title, class: "min-w-[150px]"
column :published_date, class: "min-w-[170px]"
column :author
column :category
column :starred
column :position
column :created_at, class: "min-w-[200px]"
column :updated_at, class: "min-w-[200px]"
end
member_action :toggle_starred, method: :put do
resource.update(starred: !resource.starred)
redirect_to resource_path, notice: "Post updated."
end
action_item :toggle_starred, only: :show do
link_to "Toggle Starred", toggle_starred_admin_user_post_path(resource.author, resource), method: :put, class: "action-item-button"
end
show do
attributes_table_for(resource) do
row :id
row :title
row :published_date
row :author
row :body
row :category
row :starred
row :position
row :created_at
row :updated_at
end
div class: "grid grid-cols-1 md:grid-cols-2 gap-4 my-4" do
div do
panel "Tags" do
table_for(post.taggings.order(:position)) do
column :id do |tagging|
link_to tagging.tag_id, admin_tag_path(tagging.tag)
end
column :tag, &:tag_name
column :position
column :updated_at
end
end
end
div do
panel "Category" do
attributes_table_for post.category do
row :id do |category|
link_to category.id, admin_category_path(category)
end
row :description
end
end
end
end
end
form do |f|
f.semantic_errors(*f.object.errors.attribute_names)
f.inputs "Details", class: "mb-6" do
f.input :title
f.input :author
f.input :published_date,
hint: f.object.persisted? && "Created at #{f.object.created_at}"
f.input :custom_category_id
f.input :category, hint: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tincidunt porttitor massa eu consequat. Suspendisse potenti. Curabitur gravida sem vel elit auctor ultrices."
f.input :position
f.input :starred
end
f.inputs "Content", class: "mb-6" do
f.input :body
end
f.inputs "Tags", class: "mb-6" do
f.has_many :taggings, heading: false, sortable: :position do |t|
t.input :tag
t.input :_destroy, as: :boolean
end
end
para "Press cancel to return to the list without saving.", class: "py-2"
f.actions
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/categories.rb | spec/support/templates_with_data/admin/categories.rb | # frozen_string_literal: true
ActiveAdmin.register Category do
config.create_another = true
permit_params :name, :description
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/kitchen_sink.rb | spec/support/templates_with_data/admin/kitchen_sink.rb | # frozen_string_literal: true
ActiveAdmin.register_page "KitchenSink" do
content do
panel "About ActiveAdmin" do
para class: "mb-4" do
a "Active Admin", href: "https://github.com/activeadmin/activeadmin"
text_node "is a"
span "Ruby on Rails", class: "text-red-500"
text_node "framework for"
em "creating elegant backends"
text_node "for"
strong "website administration."
end
para do
abbr "HTML", title: "HyperText Markup Language"
text_node "is the basic building block of the Web."
end
end
div class: "grid grid-cols-1 md:grid-cols-2 gap-5" do
div do
h3 "TableFor Example", class: "mb-4 text-base/7 font-semibold text-gray-900 dark:text-white"
div class: "border border-gray-200 dark:border-gray-800 rounded-md shadow-xs overflow-hidden" do
div class: "overflow-x-auto" do
table_for User.first(5) do
column :id
column :display_name, class: "min-w-40" do |user|
auto_link user
end
column :username
column :age
column :created_at, class: "min-w-40"
column :updated_at, class: "min-w-40"
end
end
end
end
div do
h3 "Attributes Table Example", class: "mb-4 text-base/7 font-semibold text-gray-900 dark:text-white"
attributes_table_for(Post.first) do
row :title
row :published_date
row :author
row :category
row :starred
row :position
end
end
end
end
sidebar "Sample Sidebar" do
div class: "pb-6" do
h3 "Applicant Information", class: "text-base/7 font-semibold text-gray-900 dark:text-white"
para "A sidebar can also be used on a custom page.", class: "mt-1 text-sm/6 text-gray-500 dark:text-gray-400"
end
dl do
div class: "border-t border-gray-100 dark:border-white/10 py-4" do
dt "Full name", class: "text-sm/6 font-medium text-gray-900 dark:text-gray-100"
dd "Margot Foster", class: "mt-1 text-sm/6 text-gray-700 dark:text-gray-400"
end
div class: "border-t border-gray-100 dark:border-white/10 py-4" do
dt "Application for", class: "text-sm/6 font-medium text-gray-900 dark:text-gray-100"
dd "Backend Developer", class: "mt-1 text-sm/6 text-gray-700 dark:text-gray-400"
end
div class: "border-t border-gray-100 dark:border-white/10 py-4" do
dt "Email address", class: "text-sm/6 font-medium text-gray-900 dark:text-gray-100"
dd "margotfoster@example.com", class: "mt-1 text-sm/6 text-gray-700 dark:text-gray-400"
end
div class: "border-t border-gray-100 dark:border-white/10 py-4" do
dt "Attachments", class: "text-sm/6 font-medium text-gray-900 dark:text-gray-100"
dd class: "mt-1 text-sm/6 text-gray-700 dark:text-gray-400" do
ul class: "divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-white/5 dark:border-white/10", role: "list" do
li class: "flex items-center justify-between py-3 pl-3 pr-4 text-sm/6" do
div class: "flex w-0 flex-1 items-center" do
text_node '<svg viewBox="0 0 20 20" fill="currentColor" data-slot="icon" aria-hidden="true" class="size-5 shrink-0 text-gray-400 dark:text-gray-500"><path d="M15.621 4.379a3 3 0 0 0-4.242 0l-7 7a3 3 0 0 0 4.241 4.243h.001l.497-.5a.75.75 0 0 1 1.064 1.057l-.498.501-.002.002a4.5 4.5 0 0 1-6.364-6.364l7-7a4.5 4.5 0 0 1 6.368 6.36l-3.455 3.553A2.625 2.625 0 1 1 9.52 9.52l3.45-3.451a.75.75 0 1 1 1.061 1.06l-3.45 3.451a1.125 1.125 0 0 0 1.587 1.595l3.454-3.553a3 3 0 0 0 0-4.242Z" clip-rule="evenodd" fill-rule="evenodd" /></svg>'.html_safe
div class: "ms-2 flex min-w-0 flex-1 gap-2" do
span class: "truncate font-medium text-gray-900 dark:text-white" do
"resume_back_end_developer.pdf"
end
span class: "shrink-0 text-gray-400 dark:text-gray-500" do
"2.4mb"
end
end
end
end
li class: "flex items-center justify-between py-3 pl-3 pr-4 text-sm/6" do
div class: "flex w-0 flex-1 items-center" do
text_node '<svg viewBox="0 0 20 20" fill="currentColor" data-slot="icon" aria-hidden="true" class="size-5 shrink-0 text-gray-400 dark:text-gray-500"><path d="M15.621 4.379a3 3 0 0 0-4.242 0l-7 7a3 3 0 0 0 4.241 4.243h.001l.497-.5a.75.75 0 0 1 1.064 1.057l-.498.501-.002.002a4.5 4.5 0 0 1-6.364-6.364l7-7a4.5 4.5 0 0 1 6.368 6.36l-3.455 3.553A2.625 2.625 0 1 1 9.52 9.52l3.45-3.451a.75.75 0 1 1 1.061 1.06l-3.45 3.451a1.125 1.125 0 0 0 1.587 1.595l3.454-3.553a3 3 0 0 0 0-4.242Z" clip-rule="evenodd" fill-rule="evenodd" /></svg>'.html_safe
div class: "ms-2 flex min-w-0 flex-1 gap-2" do
span class: "truncate font-medium text-gray-900 dark:text-white" do
"coverletter_back_end_developer.pdf"
end
span class: "shrink-0 text-gray-400 dark:text-gray-500" do
"4.5mb"
end
end
end
end
end
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/tags.rb | spec/support/templates_with_data/admin/tags.rb | # frozen_string_literal: true
ActiveAdmin.register Tag do
config.create_another = true
permit_params :name
index do
selectable_column
id_column
column :name
column :created_at
actions do |tag|
item "Preview", admin_tag_path(tag)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/support/templates_with_data/admin/components/custom_index.rb | spec/support/templates_with_data/admin/components/custom_index.rb | # frozen_string_literal: true
module ActiveAdmin
module Views
class CustomIndex < ActiveAdmin::Component
def build(page_presenter, collection)
add_class("custom-index")
set_attribute("data-index-as", "custom")
if active_admin_config.batch_actions.any?
div class: "p-3" do
resource_selection_toggle_panel
end
end
div class: "p-3 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6" do
collection.each do |obj|
instance_exec(obj, &page_presenter.block)
end
end
end
def self.index_name
"custom"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/requests/default_namespace_spec.rb | spec/requests/default_namespace_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Application, type: :request do
let(:resource) { ActiveAdmin.register Category }
[false, nil].each do |value|
describe "with a #{value} default namespace" do
around do |example|
with_custom_default_namespace(value) { example.call }
end
it "should generate resource paths" do
expect(resource.route_collection_path).to eq "/categories"
end
it "should generate a log out path" do
expect(destroy_admin_user_session_path).to eq "/logout"
end
it "should generate a log in path" do
expect(new_admin_user_session_path).to eq "/login"
end
end
end
describe "with a test default namespace" do
around do |example|
with_custom_default_namespace(:test) { example.call }
end
it "should generate resource paths" do
expect(resource.route_collection_path).to eq "/test/categories"
end
it "should generate a log out path" do
expect(destroy_admin_user_session_path).to eq "/test/logout"
end
it "should generate a log in path" do
expect(new_admin_user_session_path).to eq "/test/login"
end
end
describe "with a namespace with underscores in the name" do
around do |example|
with_custom_default_namespace(:abc_123) { example.call }
end
it "should generate resource paths" do
expect(resource.route_collection_path).to eq "/abc_123/categories"
end
it "should generate a log out path" do
expect(destroy_admin_user_session_path).to eq "/abc_123/logout"
end
it "should generate a log in path" do
expect(new_admin_user_session_path).to eq "/abc_123/login"
end
end
private
def with_custom_default_namespace(namespace)
application = ActiveAdmin::Application.new
application.default_namespace = namespace
with_temp_application(application) { yield }
end
def with_temp_application(application)
original_application = ActiveAdmin.application
ActiveAdmin.application = application
load_resources { ActiveAdmin.register(Category) }
yield
ensure
ActiveAdmin.application = original_application
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/requests/memory_spec.rb | spec/requests/memory_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Memory Leak", type: :request, if: RUBY_ENGINE == "ruby" do
around do |example|
with_resources_during(example) { ActiveAdmin.register(Category) }
end
def count_instances_of(klass)
ObjectSpace.each_object(klass) {}
end
[ActiveAdmin::Namespace, ActiveAdmin::Resource].each do |klass|
it "should not leak #{klass}" do
previously_disabled = GC.enable
GC.start
count = count_instances_of(klass)
load_resources { ActiveAdmin.register(Category) }
GC.start
GC.disable if previously_disabled
expect(count_instances_of klass).to be <= count
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/breadcrumb_helper_spec.rb | spec/helpers/breadcrumb_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::BreadcrumbHelper, type: :helper do
describe "generating a trail from paths" do
let(:actions) { ActiveAdmin::BaseController::ACTIVE_ADMIN_ACTIONS }
let(:user) { double display_name: "Jane Doe" }
let(:user_config) do
double find_resource: user, resource_name: double(route_key: "users"),
defined_actions: actions
end
let(:post) { double display_name: "Hello World" }
let(:post_config) do
double find_resource: post, resource_name: double(route_key: "posts"),
defined_actions: actions, breadcrumb: true, belongs_to_config: double(target: user_config)
end
let :active_admin_config do
post_config
end
let(:trail) do
helper.class.send(:include, ActiveAdmin::DisplayHelper)
helper.class.send(:include, ActiveAdmin::LayoutHelper)
helper.class.send(:include, MethodOrProcHelper)
allow(helper).to receive(:link_to) { |name, url| { name: name, path: url } }
allow(helper).to receive(:active_admin_config).and_return(active_admin_config)
helper.build_breadcrumb_links(path)
end
context "when request '/admin'" do
let(:path) { "/admin" }
it "should not have any items" do
expect(trail.size).to eq 0
end
end
context "when path 'admin/users'" do
let(:path) { "admin/users" }
it "should have one item" do
expect(trail.size).to eq 1
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
end
context "when path '/admin/users'" do
let(:path) { "/admin/users" }
it "should have one item" do
expect(trail.size).to eq 1
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
end
context "when path '/admin/users/1'" do
let(:path) { "/admin/users/1" }
it "should have 2 items" do
expect(trail.size).to eq 2
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
end
context "when path '/admin/users/1/posts'" do
let(:path) { "/admin/users/1/posts" }
it "should have 3 items" do
expect(trail.size).to eq 3
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
context "when User.find(1) doesn't exist" do
before { allow(user_config).to receive(:find_resource) }
it "should have a link to /admin/users/1" do
expect(trail[2][:name]).to eq "1"
expect(trail[2][:path]).to eq "/admin/users/1"
end
end
context "when User.find(1) does exist" do
it "should have a link to /admin/users/1 using display name" do
expect(trail[2][:name]).to eq "Jane Doe"
expect(trail[2][:path]).to eq "/admin/users/1"
end
end
end
context "when path '/admin/users/4e24d6249ccf967313000000/posts'" do
let(:path) { "/admin/users/4e24d6249ccf967313000000/posts" }
it "should have 3 items" do
expect(trail.size).to eq 3
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
context "when User.find(4e24d6249ccf967313000000) doesn't exist" do
before { allow(user_config).to receive(:find_resource) }
it "should have a link to /admin/users/4e24d6249ccf967313000000" do
expect(trail[2][:name]).to eq "4e24d6249ccf967313000000"
expect(trail[2][:path]).to eq "/admin/users/4e24d6249ccf967313000000"
end
end
context "when User.find(4e24d6249ccf967313000000) does exist" do
before do
display_name = double(display_name: "Hello :)")
allow(user_config).to receive(:find_resource).and_return(display_name)
end
it "should have a link to /admin/users/4e24d6249ccf967313000000 using display name" do
expect(trail[2][:name]).to eq "Hello :)"
expect(trail[2][:path]).to eq "/admin/users/4e24d6249ccf967313000000"
end
end
end
context "when path '/admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4/posts'" do
let(:path) { "/admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4/posts" }
it "should have 3 items" do
expect(trail.size).to eq 3
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
context "when User.find(2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4) doesn't exist" do
before { allow(user_config).to receive(:find_resource) }
it "should have a link to /admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4" do
expect(trail[2][:name]).to eq "2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4".titlecase
expect(trail[2][:path]).to eq "/admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4"
end
end
context "when User.find(2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4) does exist" do
before do
display_name = double(display_name: "Hello :)")
allow(user_config).to receive(:find_resource).and_return(display_name)
end
it "should have a link to /admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4 using display name" do
expect(trail[2][:name]).to eq "Hello :)"
expect(trail[2][:path]).to eq "/admin/users/2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4"
end
end
end
context "when path '/admin/users/1/posts/1'" do
let(:path) { "/admin/users/1/posts/1" }
it "should have 4 items" do
expect(trail.size).to eq 4
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
it "should have a link to /admin/users/1" do
expect(trail[2][:name]).to eq "Jane Doe"
expect(trail[2][:path]).to eq "/admin/users/1"
end
it "should have a link to /admin/users/1/posts" do
expect(trail[3][:name]).to eq "Posts"
expect(trail[3][:path]).to eq "/admin/users/1/posts"
end
end
context "when path '/admin/users/1/posts/1/edit'" do
let(:path) { "/admin/users/1/posts/1/edit" }
it "should have 5 items" do
expect(trail.size).to eq 5
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/users" do
expect(trail[1][:name]).to eq "Users"
expect(trail[1][:path]).to eq "/admin/users"
end
it "should have a link to /admin/users/1" do
expect(trail[2][:name]).to eq "Jane Doe"
expect(trail[2][:path]).to eq "/admin/users/1"
end
it "should have a link to /admin/users/1/posts" do
expect(trail[3][:name]).to eq "Posts"
expect(trail[3][:path]).to eq "/admin/users/1/posts"
end
it "should have a link to /admin/users/1/posts/1" do
expect(trail[4][:name]).to eq "Hello World"
expect(trail[4][:path]).to eq "/admin/users/1/posts/1"
end
end
context "when the 'show' action is disabled" do
let(:post_config) do
double find_resource: post, resource_name: double(route_key: "posts"),
defined_actions: actions - [:show], # this is the change
breadcrumb: true,
belongs_to_config: double(target: user_config)
end
let(:path) { "/admin/posts/1/edit" }
it "should have 3 items" do
expect(trail.size).to eq 3
end
it "should have a link to /admin" do
expect(trail[0][:name]).to eq "Admin"
expect(trail[0][:path]).to eq "/admin"
end
it "should have a link to /admin/posts" do
expect(trail[1][:name]).to eq "Posts"
expect(trail[1][:path]).to eq "/admin/posts"
end
it "should not link to the show view for the post" do
expect(trail[2]).to eq "Hello World"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/layout_helper_spec.rb | spec/helpers/layout_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::LayoutHelper, type: :helper do
describe "active_admin_application" do
it "returns the application instance" do
expect(helper.active_admin_application).to eq ActiveAdmin.application
end
end
describe "set_page_title" do
it "sets the @page_title variable" do
helper.set_page_title("Sample Page")
expect(helper.instance_variable_get(:@page_title)).to eq "Sample Page"
end
end
describe "html_head_site_title" do
before do
expect(helper).to receive(:site_title).and_return("MyAdmin")
allow(helper).to receive(:page_title).and_return("Users")
end
it "returns title in default format" do
expect(helper.html_head_site_title).to eq "Users - MyAdmin"
end
it "returns title with custom separator" do
expect(helper.html_head_site_title(separator: "|")).to eq "Users | MyAdmin"
end
it "returns title with @page_title override" do
helper.set_page_title("Posts")
expect(helper.html_head_site_title).to eq "Posts - MyAdmin"
end
end
describe "skip_sidebar?" do
it "should return true if skipped" do
helper.skip_sidebar!
expect(helper.skip_sidebar?).to eq true
end
it "should return false if not skipped" do
expect(helper.skip_sidebar?).to eq false
end
end
describe ".flash_messages" do
it "should not include 'timedout' flash messages by default" do
expect(helper).to receive(:active_admin_application).and_return(ActiveAdmin::Application.new)
flash[:alert] = "Alert"
flash[:timedout] = true
expect(helper.flash_messages).to include "alert"
expect(helper.flash_messages).to_not include "timedout"
end
it "should not return flash messages included in flash_keys_to_except config" do
config = double(flash_keys_to_except: ["hideme"])
expect(helper).to receive(:active_admin_application).and_return(config)
flash[:alert] = "Alert"
flash[:hideme] = "Do not show"
expect(helper.flash_messages).to include "alert"
expect(helper.flash_messages).to_not include "hideme"
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/display_helper_spec.rb | spec/helpers/display_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::DisplayHelper, type: :helper do
let(:active_admin_namespace) { helper.active_admin_application.namespaces[:admin] }
let(:displayed_name) { helper.display_name(resource) }
before do
helper.class.send(:include, ActiveAdmin::LayoutHelper)
helper.class.send(:include, ActiveAdmin::AutoLinkHelper)
helper.class.send(:include, MethodOrProcHelper)
allow(helper).to receive(:authorized?).and_return(true)
allow(helper).to receive(:active_admin_namespace).and_return(active_admin_namespace)
allow(helper).to receive(:url_options).and_return(locale: nil)
load_resources do
ActiveAdmin.register(User)
ActiveAdmin.register(Post) { belongs_to :user, optional: true }
end
end
describe "display name fallback constant" do
let(:fallback_proc) { described_class::DISPLAY_NAME_FALLBACK }
it "sets the proc to be inspectable" do
expect(fallback_proc.inspect).to eq "DISPLAY_NAME_FALLBACK"
end
it "returns a primary key only if class has no model name" do
resource_class = Class.new do
def self.primary_key
:id
end
def id
123
end
end
expect(helper.render_in_context(resource_class.new, fallback_proc)).to eq " #123"
end
end
describe "#display_name" do
let(:resource) { klass.new }
ActiveAdmin::Application.new.display_name_methods.map(&:to_s).each do |m|
context "when it is the identity" do
let(:klass) do
Class.new do
define_method(m) { m }
end
end
it "should return #{m}" do
expect(displayed_name).to eq m
end
end
context "when it includes js" do
let(:klass) do
Class.new do
define_method(m) { "<script>alert(1)</script>" }
end
end
it "should sanitize the result of #{m}" do
expect(displayed_name).to eq "<script>alert(1)</script>"
end
end
end
describe "memoization" do
let(:klass) { Class.new }
it "should memoize the result for the class" do
expect(resource).to receive(:name).and_return "My Name"
expect(displayed_name).to eq "My Name"
expect(ActiveAdmin.application).to_not receive(:display_name_methods)
expect(displayed_name).to eq "My Name"
end
it "should not call a method if it's an association" do
allow(klass).to receive(:reflect_on_all_associations).and_return [ double(name: :login) ]
allow(resource).to receive :login
expect(resource).to_not receive :login
allow(resource).to receive(:email).and_return "foo@bar.baz"
expect(displayed_name).to eq "foo@bar.baz"
end
end
context "when the passed object is `nil`" do
let(:resource) { nil }
it "should return `nil` when the passed object is `nil`" do
expect(displayed_name).to eq nil
end
end
context "when the passed object is `false`" do
let(:resource) { false }
it "should return 'false' when the passed object is `false`" do
expect(displayed_name).to eq "false"
end
end
describe "default implementation" do
let(:klass) { Class.new }
it "should default to `to_s`" do
result = resource.to_s
expect(displayed_name).to eq ERB::Util.html_escape(result)
end
end
context "when no display name method is defined" do
context "when no ID" do
let(:resource) do
class ThisModel
extend ActiveModel::Naming
end
ThisModel.new
end
it "should show the model name" do
expect(displayed_name).to eq "This model"
end
end
context "when ID" do
let(:resource) { Tagging.create! }
it "should show the model name, plus the ID if in use" do
expect(displayed_name).to eq "Tagging #1"
end
it "should translate the model name" do
with_translation %i[activerecord models tagging one], "Different" do
expect(displayed_name).to eq "Different #1"
end
end
end
end
end
describe "#format_attribute" do
it "calls the provided block to format the value" do
value = helper.format_attribute double(foo: 2), ->r { r.foo + 1 }
expect(value).to eq "3"
end
it "finds values as methods" do
value = helper.format_attribute double(name: "Joe"), :name
expect(value).to eq "Joe"
end
it "finds values from hashes" do
value = helper.format_attribute({ id: 100 }, :id)
expect(value).to eq "100"
end
[1, 1.2, :a_symbol].each do |val|
it "calls to_s to format the value of type #{val.class}" do
value = helper.format_attribute double(foo: val), :foo
expect(value).to eq val.to_s
end
end
it "localizes dates" do
date = Date.parse "2016/02/28"
value = helper.format_attribute double(date: date), :date
expect(value).to eq "February 28, 2016"
end
it "localizes times" do
time = Time.parse "2016/02/28 9:34 PM"
value = helper.format_attribute double(time: time), :time
expect(value).to eq "February 28, 2016 21:34"
end
it "uses a display_name method for arbitrary objects" do
object = double to_s: :wrong, display_name: :right
value = helper.format_attribute double(object: object), :object
expect(value).to eq "right"
end
it "auto-links ActiveRecord records by association with display name fallback" do
post = Post.create! author: User.new(first_name: "", last_name: "")
value = helper.format_attribute post, :author
expect(value).to match(/<a href="\/admin\/users\/\d+">User \#\d+<\/a>/)
end
it "auto-links ActiveRecord records & uses a display_name method" do
post = Post.create! author: User.new(first_name: "A", last_name: "B")
value = helper.format_attribute post, :author
expect(value).to match(/<a href="\/admin\/users\/\d+">A B<\/a>/)
end
it "calls status_tag for boolean values" do
post = Post.new starred: true
value = helper.format_attribute post, :starred
expect(value.to_s).to eq "<span class=\"status-tag\" data-status=\"yes\">Yes</span>\n"
end
context "with non-database boolean attribute" do
let(:model_class) do
Class.new(Post) do
attribute :a_virtual_attribute, :boolean
end
end
it "calls status_tag even when attribute is nil" do
post = model_class.new a_virtual_attribute: nil
value = helper.format_attribute post, :a_virtual_attribute
expect(value.to_s).to eq "<span class=\"status-tag\" data-status=\"unset\">Unknown</span>\n"
end
end
it "calls status_tag for boolean non-database values" do
post = Post.new
post.define_singleton_method(:true_method) do
true
end
post.define_singleton_method(:false_method) do
false
end
true_value = helper.format_attribute post, :true_method
expect(true_value.to_s).to eq "<span class=\"status-tag\" data-status=\"yes\">Yes</span>\n"
false_value = helper.format_attribute post, :false_method
expect(false_value.to_s).to eq "<span class=\"status-tag\" data-status=\"no\">No</span>\n"
end
it "renders ActiveRecord relations as a list" do
tags = (1..3).map do |i|
Tag.create!(name: "abc#{i}")
end
post = Post.create!(tags: tags)
value = helper.format_attribute post, :tags
expect(value.to_s).to eq "abc1, abc2, abc3"
end
it "renders arrays as a list" do
items = (1..3).map { |i| "abc#{i}" }
post = Post.create!
allow(post).to receive(:items).and_return(items)
value = helper.format_attribute post, :items
expect(value.to_s).to eq "abc1, abc2, abc3"
end
end
describe "#pretty_format" do
let(:formatted_obj) { helper.pretty_format(obj) }
shared_examples_for "an object convertible to string" do
it "should call `to_s` on the given object" do
expect(formatted_obj).to eq obj.to_s
end
end
context "when given a string" do
let(:obj) { "hello" }
it_behaves_like "an object convertible to string"
end
context "when given an integer" do
let(:obj) { 23 }
it_behaves_like "an object convertible to string"
end
context "when given a float" do
let(:obj) { 5.67 }
it_behaves_like "an object convertible to string"
end
context "when given an exponential" do
let(:obj) { 10**30 }
it_behaves_like "an object convertible to string"
end
context "when given a symbol" do
let(:obj) { :foo }
it_behaves_like "an object convertible to string"
end
context "when given an arbre element" do
let(:obj) { Arbre::Element.new.br }
it_behaves_like "an object convertible to string"
end
shared_examples_for "a time-ish object" do
it "formats it with the default long format" do
expect(formatted_obj).to eq "February 28, 1985 20:15"
end
it "formats it with a customized long format" do
with_translation %i[time formats long], "%B %d, %Y, %l:%M%P" do
expect(formatted_obj).to eq "February 28, 1985, 8:15pm"
end
end
context "with a custom localize format" do
around do |example|
previous_localize_format = ActiveAdmin.application.localize_format
ActiveAdmin.application.localize_format = :short
example.call
ActiveAdmin.application.localize_format = previous_localize_format
end
it "formats it with the default custom format" do
expect(formatted_obj).to eq "28 Feb 20:15"
end
it "formats it with i18n custom format" do
with_translation %i[time formats short], "%-m %d %Y" do
expect(formatted_obj).to eq "2 28 1985"
end
end
end
context "with non-English locale" do
around do |example|
I18n.with_locale(:es, &example)
end
it "formats it with the default long format" do
expect(formatted_obj).to eq "28 de febrero de 1985 20:15"
end
it "formats it with a customized long format" do
with_translation %i[time formats long], "El %d de %B de %Y a las %H horas y %M minutos" do
expect(formatted_obj).to eq "El 28 de febrero de 1985 a las 20 horas y 15 minutos"
end
end
end
end
context "when given a Time in utc" do
let(:obj) { Time.utc(1985, "feb", 28, 20, 15, 1) }
it_behaves_like "a time-ish object"
end
context "when given a DateTime" do
let(:obj) { DateTime.new(1985, 2, 28, 20, 15, 1) }
it_behaves_like "a time-ish object"
end
context "given an ActiveRecord object" do
let(:obj) { Post.new }
it "should delegate to auto_link" do
expect(view).to receive(:auto_link).with(obj).and_return("model name")
expect(formatted_obj).to eq "model name"
end
end
context "given an arbitrary object" do
let(:obj) { Class.new.new }
it "should delegate to `display_name`" do
expect(view).to receive(:display_name).with(obj) { "I'm not famous" }
expect(formatted_obj).to eq "I'm not famous"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/filter_form_helper_spec.rb | spec/helpers/filter_form_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::FormHelper, type: :helper do
def render_filter(search, filters)
allow(helper).to receive(:collection_path).and_return("/posts")
allow(helper).to receive(:a_helper_method).and_return("A Helper Method")
render_arbre_component({ filter_args: [search, filters] }, helper) do
args = assigns[:filter_args]
kwargs = args.pop if args.last.is_a?(Hash)
text_node active_admin_filters_form_for(*args, **kwargs)
end.to_s
end
def filter(name, options = {})
Capybara.string(render_filter(scope, name => options))
end
let(:scope) { Post.ransack }
before do
helper.class.send(:include, MethodOrProcHelper)
end
describe "the form in general" do
let(:body) { filter :title }
it "should generate a form which submits via get" do
expect(body).to have_css("form.filters-form[method=get]")
end
it "should generate a filter button" do
expect(body).to have_button('Filter')
end
it "should only generate the form once" do
expect(body).to have_css("form", count: 1)
end
it "should generate a clear filters link" do
expect(body).to have_link("Clear Filters", class: "filters-form-clear")
end
describe "label as proc" do
let(:body) { filter :title, label: proc { "Title from proc" } }
it "should render proper label" do
expect(body).to have_css("label", text: "Title from proc")
end
end
describe "input html as proc" do
let(:body) { filter :title, as: :select, input_html: proc { { 'data-ajax-url': "/" } } }
it "should render proper label" do
expect(body).to have_css('select[data-ajax-url="/"]')
end
end
end
describe "string attribute" do
let(:body) { filter :title }
it "should generate a select option for starts with" do
expect(body).to have_css("option[value=title_start]", text: "Starts with")
end
it "should generate a select option for ends with" do
expect(body).to have_css("option[value=title_end]", text: "Ends with")
end
it "should generate a select option for contains" do
expect(body).to have_css("option[value=title_cont]", text: "Contains")
end
it "should generate a text field for input" do
expect(body).to have_field("q[title_cont]")
end
it "should have a proper label" do
expect(body).to have_css("label", text: "Title")
end
it "should translate the label for text field" do
with_translation %i[activerecord attributes post title], "Name" do
expect(body).to have_css("label", text: "Name")
end
end
it "should select the option which is currently being filtered" do
scope = Post.ransack title_start: "foo"
body = Capybara.string(render_filter scope, title: {})
expect(body).to have_css("option[value=title_start][selected=selected]", text: "Starts with")
end
context "with filters options" do
let(:body) { filter :title, filters: [:cont, :start] }
it "should generate provided options for filter select" do
expect(body).to have_css("option[value=title_cont]", text: "Contains")
expect(body).to have_css("option[value=title_start]", text: "Starts with")
end
it "should not generate a select option for ends with" do
expect(body).to have_no_css("option[value=title_end]")
end
end
context "with predicate" do
%w[eq cont start end].each do |predicate|
describe "'#{predicate}'" do
let(:body) { filter :"title_#{predicate}" }
it "shouldn't include a select field" do
expect(body).to have_no_select
end
it "should build correctly" do
expect(body).to have_field("q[title_#{predicate}]")
end
end
end
end
end
describe "string attribute ended with ransack predicate" do
let(:scope) { User.ransack }
let(:body) { filter :reason_of_sign_in }
it "should generate a select options" do
expect(body).to have_css("option[value=reason_of_sign_in_start]")
expect(body).to have_css("option[value=reason_of_sign_in_end]")
expect(body).to have_css("option[value=reason_of_sign_in_cont]")
end
end
describe "text attribute" do
let(:body) { filter :body }
it "should generate a search field for a text attribute" do
expect(body).to have_field("q[body_cont]")
end
it "should have a proper label" do
expect(body).to have_css("label", text: "Body")
end
end
describe "string attribute, as a select" do
let(:body) { filter :title, as: :select }
let(:builder) { ActiveAdmin::Inputs::Filters::SelectInput }
context "when loading collection from DB" do
it "should use pluck for efficiency" do
expect_any_instance_of(builder).to receive(:pluck_column) { [] }
body
end
it "should remove original ordering to prevent PostgreSQL error" do
expect(scope.object.klass).to receive(:reorder).with("title asc") {
m = double distinct: double(pluck: ["A Title"])
expect(m.distinct).to receive(:pluck).with :title
m
}
body
end
context "and a statement timeout error occurs" do
let(:body) { filter :title, as: :select, collection: ["foo"] }
let(:input_super_class) { Formtastic::Inputs::Base::Collections }
let(:db_timeout_exception) { ActiveRecord::QueryCanceled.new("ERROR: canceling statement due to statement timeout") }
let(:expected_exception_message) { "ERROR: canceling statement due to statement timeout while querying the values for the ActiveAdmin :title filter" }
before do
expect_any_instance_of(input_super_class).to receive(:collection).and_raise(db_timeout_exception)
end
it "should raise a database timeout error with a message indicating which filter was the cause" do
expect { body }.to raise_error(ActiveRecord::QueryCanceled, expected_exception_message)
end
end
end
end
describe "date attribute" do
let(:body) { filter :published_date }
it "should generate a date greater than" do
expect(body).to have_field("q[published_date_gteq]", class: "datepicker")
end
it "should generate a date less than" do
expect(body).to have_field("q[published_date_lteq]", class: "datepicker")
end
it "should generate two inputs with different ids" do
ids = body.find_css("input.datepicker").to_a.map { |n| n[:id] }
expect(ids).to contain_exactly("q_published_date_lteq", "q_published_date_gteq")
end
it "should generate one label without for attribute" do
label = body.find_css("label")
expect(label.length).to be(1)
expect(label.attr("for")).to be_nil
end
context "with input_html" do
let(:body) { filter :published_date, input_html: { 'autocomplete': "off" } }
it "should generate provided input html for both ends of date range" do
expect(body).to have_css("input.datepicker[name='q[published_date_gteq]'][autocomplete=off]")
expect(body).to have_css("input.datepicker[name='q[published_date_lteq]'][autocomplete=off]")
end
end
context "with input_html overriding the defaults" do
let(:body) { filter :published_date, input_html: { 'class': "custom_class" } }
it "should override the default attribute values for both ends of date range" do
expect(body).to have_field("q[published_date_gteq]", class: "custom_class")
expect(body).to have_field("q[published_date_lteq]", class: "custom_class")
end
end
end
describe "datetime attribute" do
let(:body) { filter :created_at }
it "should generate a date greater than" do
expect(body).to have_field("q[created_at_gteq]", class: "datepicker")
end
it "should generate a date less than" do
expect(body).to have_field("q[created_at_lteq]", class: "datepicker")
end
context "with input_html" do
let(:body) { filter :created_at, input_html: { 'autocomplete': "off" } }
it "should generate provided input html for both ends of date range" do
expect(body).to have_css("input.datepicker[name='q[created_at_gteq]'][autocomplete=off]")
expect(body).to have_css("input.datepicker[name='q[created_at_lteq]'][autocomplete=off]")
end
end
context "with input_html overriding the defaults" do
let(:body) { filter :created_at, input_html: { 'class': "custom_class" } }
it "should override the default attribute values for both ends of date range" do
expect(body).to have_field("q[created_at_gteq]", class: "custom_class")
expect(body).to have_field("q[created_at_lteq]", class: "custom_class")
end
end
end
describe "integer attribute" do
context "without options" do
let(:body) { filter :id }
it "should generate a select option for equal to" do
expect(body).to have_css("option[value=id_eq]", text: "Equals")
end
it "should generate a select option for greater than" do
expect(body).to have_css("option[value=id_gt]", text: "Greater than")
end
it "should generate a select option for less than" do
expect(body).to have_css("option[value=id_lt]", text: "Less than")
end
it "should generate a text field for input" do
expect(body).to have_field("q[id_eq]")
end
it "should select the option which is currently being filtered" do
scope = Post.ransack id_gt: 1
body = Capybara.string(render_filter scope, id: {})
expect(body).to have_css("option[value=id_gt][selected=selected]", text: "Greater than")
end
end
context "with filters options" do
let(:body) { filter :id, filters: [:eq, :gt] }
it "should generate provided options for filter select" do
expect(body).to have_css("option[value=id_eq]", text: "Equals")
expect(body).to have_css("option[value=id_gt]", text: "Greater than")
end
it "should not generate a select option for less than" do
expect(body).to have_no_css("option[value=id_lt]")
end
end
end
describe "boolean attribute" do
context "boolean datatypes" do
let(:body) { filter :starred }
it "should generate a select" do
expect(body).to have_select("q[starred_eq]")
end
it "should set the default text to 'Any'" do
expect(body).to have_css("option[value='']", text: "Any")
end
it "should create an option for true and false" do
expect(body).to have_css("option[value=true]", text: "Yes")
expect(body).to have_css("option[value=false]", text: "No")
end
it "should translate the label for boolean field" do
with_translation %i[activerecord attributes post starred], "Faved" do
expect(body).to have_css("label", text: "Faved")
end
end
end
context "non-boolean data types" do
let(:body) { filter :title_present, as: :boolean }
it "should generate a select" do
expect(body).to have_select("q[title_present]")
end
it "should set the default text to 'Any'" do
expect(body).to have_css("option[value='']", text: "Any")
end
it "should create an option for true and false" do
expect(body).to have_css("option[value=true]", text: "Yes")
expect(body).to have_css("option[value=false]", text: "No")
end
end
end
describe "belongs_to" do
before do
@john = User.create first_name: "John", last_name: "Doe", username: "john_doe"
@jane = User.create first_name: "Jane", last_name: "Doe", username: "jane_doe"
end
context "when given as the _id attribute name" do
let(:body) { filter :author_id }
it "should generate a numeric filter" do
expect(body).to have_css("label", text: "Author") # really this should be Author ID :/)
expect(body).to have_css("option[value=author_id_lt]")
expect(body).to have_field("q[author_id_eq]", id: "q_author_id")
end
end
context "when given as the name of the relationship" do
let(:body) { filter :author }
it "should generate a select" do
expect(body).to have_select("q[author_id_eq]")
end
it "should set the default text to 'Any'" do
expect(body).to have_css("option[value='']", text: "Any")
end
it "should create an option for each related object" do
expect(body).to have_css("option[value='#{@john.id}']", text: "John Doe")
expect(body).to have_css("option[value='#{@jane.id}']", text: "Jane Doe")
end
context "with a proc" do
let :body do
filter :title, as: :select, collection: proc { ["Title One", "Title Two"] }
end
it "should use call the proc as the collection" do
expect(body).to have_css("option", text: "Title One")
expect(body).to have_css("option", text: "Title Two")
end
it "should render the collection in the context of the view" do
body = filter :title, as: :select, collection: proc { [a_helper_method] }
expect(body).to have_css("option", text: "A Helper Method")
end
end
end
context "when given the name of relationship with a primary key other than id" do
let(:resource_klass) do
Class.new(Post) do
belongs_to :kategory, class_name: "Category", primary_key: :name, foreign_key: :title
def self.name
"SuperPost"
end
end
end
let(:scope) do
resource_klass.ransack
end
let(:body) { filter :kategory }
it "should use the association primary key" do
expect(body).to have_select("q[kategory_name_eq]")
end
end
context "as check boxes" do
let(:body) { filter :author, as: :check_boxes }
it "should create a check box for each related object" do
expect(body).to have_field("q[author_id_in][]", type: :checkbox, with: @jane.id)
expect(body).to have_field("q[author_id_in][]", type: :checkbox, with: @jane.id)
end
end
context "when polymorphic relationship" do
let(:scope) { ActiveAdmin::Comment.ransack }
it "should raise an error if a collection isn't provided" do
expect { filter :resource }.to raise_error \
Formtastic::PolymorphicInputWithoutCollectionError
end
end
context "when using a custom foreign key" do
let(:scope) { Post.ransack }
let(:body) { filter :category }
it "should ignore that foreign key and let Ransack handle it" do
expect(Post.reflect_on_association(:category).foreign_key.to_sym).to eq :custom_category_id
expect(body).to have_select("q[category_id_eq]")
end
end
end # belongs to
describe "has_and_belongs_to_many" do
# skip "add HABTM models so this can be tested"
end
describe "has_many :through" do
let(:scope) { Category.ransack }
let!(:john) { User.create first_name: "John", last_name: "Doe", username: "john_doe" }
let!(:jane) { User.create first_name: "Jane", last_name: "Doe", username: "jane_doe" }
context "when given as the name of the relationship" do
let(:body) { filter :authors }
it "should generate a select" do
expect(body).to have_select("q[posts_author_id_eq]")
end
it "should set the default text to 'Any'" do
expect(body).to have_css("option[value='']", text: "Any")
end
it "should create an option for each related object" do
expect(body).to have_css("option[value='#{john.id}']", text: "John Doe")
expect(body).to have_css("option[value='#{jane.id}']", text: "Jane Doe")
end
end
context "as check boxes" do
let(:body) { filter :authors, as: :check_boxes }
it "should create a check box for each related object" do
expect(body).to have_field("q[posts_author_id_in][]", type: "checkbox", with: john.id)
expect(body).to have_field("q[posts_author_id_in][]", type: "checkbox", with: jane.id)
end
end
end
describe "conditional display" do
[:if, :unless].each do |verb|
should = verb == :if ? "should" : "shouldn't"
if_true = verb == :if ? :to : :to_not
if_false = verb == :if ? :to_not : :to
context "with #{verb.inspect} proc" do
it "#{should} be displayed if true" do
body = filter :body, verb => proc { true }
expect(body).send if_true, have_field("q[body_cont]")
end
it "#{should} be displayed if false" do
body = filter :body, verb => proc { false }
expect(body).send if_false, have_field("q[body_cont]")
end
it "should still be hidden on the second render" do
filters = { body: { verb => proc { verb == :unless } } }
2.times do
body = Capybara.string(render_filter scope, filters)
expect(body).to have_no_field("q[body_cont]")
end
end
it "should successfully keep rendering other filters after one is hidden" do
filters = { body: { verb => proc { verb == :unless } }, author: {} }
body = Capybara.string(render_filter scope, filters)
expect(body).to have_no_field("q[body_cont]")
expect(body).to have_select("q[author_id_eq]")
end
end
end
end
describe "custom search methods" do
it "should use the default type of the ransacker" do
body = filter :custom_searcher_numeric
expect(body).to have_css("option[value=custom_searcher_numeric_eq]")
expect(body).to have_css("option[value=custom_searcher_numeric_gt]")
expect(body).to have_css("option[value=custom_searcher_numeric_lt]")
end
it "should work as select" do
body = filter :custom_title_searcher, as: :select, collection: ["foo"]
expect(body).to have_select("q[custom_title_searcher_eq]")
end
it "should work as string" do
body = filter :custom_title_searcher, as: :string
expect(body).to have_css("option[value=custom_title_searcher_cont]")
expect(body).to have_css("option[value=custom_title_searcher_start]")
end
describe "custom date range search" do
let(:gteq) { "2010-10-01" }
let(:lteq) { "2010-10-02" }
let(:scope) { Post.ransack custom_created_at_searcher_gteq: gteq, custom_created_at_searcher_lteq: lteq }
let(:body) { filter :custom_created_at_searcher, as: :date_range }
it "should work as date_range" do
expect(body).to have_field("q[custom_created_at_searcher_gteq]", with: "2010-10-01")
expect(body).to have_field("q[custom_created_at_searcher_lteq]", with: "2010-10-02")
end
context "filter value can't be casted to date" do
let(:gteq) { "Ooops" }
let(:lteq) { "Ooops" }
it "should work display empty filter values" do
expect(body).to have_field("q[custom_created_at_searcher_gteq]", with: "")
expect(body).to have_field("q[custom_created_at_searcher_lteq]", with: "")
end
end
end
end
describe "does not support some filter inputs" do
it "should fallback to use formtastic inputs" do
body = filter :custom_title_searcher, as: :text
expect(body).to have_css("textarea[name='q[custom_title_searcher]']")
end
end
describe "blank option" do
context "for a select filter" do
it "should be there by default" do
body = filter :author
expect(body).to have_css("option", text: "Any")
end
it "should be able to be disabled" do
body = filter :author, include_blank: false
expect(body).to have_no_css("option", text: "Any")
end
end
context "for a multi-select filter" do
it "should not be there by default" do
body = filter :author, multiple: true
expect(body).to have_no_css("option", text: "Any")
end
it "should be able to be enabled" do
body = filter :author, multiple: true, include_blank: true
expect(body).to have_css("option", text: "Any")
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/auto_link_helper_spec.rb | spec/helpers/auto_link_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::AutoLinkHelper, type: :helper do
let(:linked_post) { helper.auto_link(post) }
let(:active_admin_namespace) { ActiveAdmin.application.namespace(:admin) }
let(:post) { Post.create! title: "Hello World" }
before do
helper.class.send(:include, ActiveAdmin::DisplayHelper)
helper.class.send(:include, ActiveAdmin::LayoutHelper)
helper.class.send(:include, MethodOrProcHelper)
allow(helper).to receive(:authorized?).and_return(true)
allow(helper).to receive(:active_admin_namespace).and_return(active_admin_namespace)
allow(helper).to receive(:url_options).and_return({})
end
context "when the resource is not registered" do
before do
load_resources {}
end
it "should return the display name of the object" do
expect(linked_post).to eq "Hello World"
end
end
context "when the resource is registered" do
before do
load_resources do
active_admin_namespace.register Post
end
end
it "should return a link with the display name of the object" do
expect(linked_post).to \
match(%r{<a href="/admin/posts/\d+">Hello World</a>})
end
it "should keep locale in the url if present" do
expect(helper).to receive(:url_options).and_return(locale: "en")
expect(linked_post).to \
match(%r{<a href="/admin/posts/\d+\?locale=en">Hello World</a>})
end
context "but the user doesn't have access" do
before do
allow(helper).to receive(:authorized?).and_return(false)
end
it "should return the display name of the object" do
expect(linked_post).to eq "Hello World"
end
end
end
context "when the resource is registered with the show action disabled" do
before do
load_resources do
active_admin_namespace.register(Post) { actions :all, except: :show }
end
end
it "should fallback to edit" do
expect(linked_post).to \
match(%r{<a href="/admin/posts/\d+/edit">Hello World</a>})
end
it "should keep locale in the url if present" do
expect(helper).to receive(:url_options).and_return(locale: "en")
expect(linked_post).to \
match(%r{<a href="/admin/posts/\d+/edit\?locale=en">Hello World</a>})
end
end
context "when the resource is registered with the show & edit actions disabled" do
before do
load_resources do
active_admin_namespace.register(Post) do
actions :all, except: [:show, :edit]
end
end
end
it "should return the display name of the object" do
expect(linked_post).to eq "Hello World"
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/index_helper_spec.rb | spec/helpers/index_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::IndexHelper, type: :helper do
describe "#collection_size" do
before do
Post.create!(title: "A post")
Post.create!(title: "A post")
Post.create!(title: "Another post")
end
it "should take the defined collection by default" do
expect(helper).to receive(:collection).and_return(Post.where(nil))
expect(helper.collection_size).to eq 3
expect(helper).to receive(:collection).and_return(Post.where(title: "Another post"))
expect(helper.collection_size).to eq 1
expect(helper).to receive(:collection).and_return(Post.where(title: "A post").to_a)
expect(helper.collection_size).to eq 2
end
context "with argument" do
it "should return the collection size for an ActiveRecord class" do
expect(helper.collection_size(Post.where(nil))).to eq 3
end
it "should return the collection size for an ActiveRecord::Relation" do
expect(helper.collection_size(Post.where(title: "A post"))).to eq 2
end
it "should return the collection size for a collection with group by" do
expect(helper.collection_size(Post.group(:title))).to eq 2
end
it "should return the collection size for a collection with group by, select and custom order" do
expect(helper.collection_size(Post.select("title, count(*) as nb_posts").group(:title).order("nb_posts"))).to eq 2
end
it "should return the collection size for an Array" do
expect(helper.collection_size(Post.where(title: "A post").to_a)).to eq 2
end
end
end
describe "#collection_empty?" do
it "should take the defined collection by default" do
expect(helper).to receive(:collection).twice.and_return(Post.all)
expect(helper.collection_empty?).to eq true
Post.create!(title: "Title")
expect(helper.collection_empty?).to eq false
end
context "with argument" do
before do
Post.create!(title: "A post")
Post.create!(title: "Another post")
end
it "should return true when the collection is empty" do
expect(helper.collection_empty?(Post.where(title: "Non existing post"))).to eq true
end
it "should return false when the collection is not empty" do
expect(helper.collection_empty?(Post.where(title: "A post"))).to eq false
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/helpers/form_helper_spec.rb | spec/helpers/form_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::FormHelper, type: :helper do
describe ".active_admin_form_for" do
let(:resource) { double "resource" }
it "calls semantic_form_for with the ActiveAdmin form builder" do
expect(helper).to receive(:semantic_form_for).with(resource, { builder: ActiveAdmin::FormBuilder })
helper.active_admin_form_for(resource)
end
it "allows the form builder to be customized" do
# We can't use a stub here because options gets marshalled, and a new
# instance built. Any constant will work.
custom_builder = Object
expect(helper).to receive(:semantic_form_for).with(resource, { builder: custom_builder })
helper.active_admin_form_for(resource, builder: custom_builder)
end
end
describe ".hidden_field_tags_for" do
it "should render hidden field tags for params" do
params = ActionController::Parameters.new(scope: "All", filter: "None")
html = Capybara.string helper.hidden_field_tags_for(params)
expect(html).to have_field("scope", id: "hidden_active_admin_scope", type: :hidden, with: "All")
expect(html).to have_field("filter", id: "hidden_active_admin_filter", type: :hidden, with: "None")
end
it "should generate not default id for hidden input" do
params = ActionController::Parameters.new(scope: "All")
expect(helper.hidden_field_tags_for(params)[/id="([^"]+)"/, 1]).to_not eq "scope"
end
it "should filter out the field passed via the option :except" do
params = ActionController::Parameters.new(scope: "All", filter: "None")
html = Capybara.string helper.hidden_field_tags_for(params, except: :filter)
expect(html).to have_field("scope", id: "hidden_active_admin_scope", type: :hidden, with: "All")
end
end
describe ".fields_for_params" do
it "should skip :action, :controller and :commit" do
expect(helper.fields_for_params(scope: "All", action: "index", controller: "PostController", commit: "Filter", utf8: "Yes!")).to eq [ { scope: "All" } ]
end
it "should skip the except" do
expect(helper.fields_for_params({ scope: "All", name: "Greg" }, except: :name)).to eq [ { scope: "All" } ]
end
it "should allow an array for the except" do
expect(helper.fields_for_params({ scope: "All", name: "Greg", age: "12" }, except: [:name, :age])).to eq [ { scope: "All" } ]
end
it "should work with hashes" do
params = helper.fields_for_params(filters: { name: "John", age: "12" })
expect(params.size).to eq 2
expect(params).to include({ "filters[name]" => "John" })
expect(params).to include({ "filters[age]" => "12" })
end
it "should work with nested hashes" do
expect(helper.fields_for_params(filters: { user: { name: "John" } })).to eq [ { "filters[user][name]" => "John" } ]
end
it "should work with arrays" do
expect(helper.fields_for_params(people: ["greg", "emily", "philippe"])).
to eq [ { "people[]" => "greg" },
{ "people[]" => "emily" },
{ "people[]" => "philippe" } ]
end
it "should work with symbols" do
expect(helper.fields_for_params(filter: :id)).to eq [ { filter: "id" } ]
end
it "should work with booleans" do
expect(helper.fields_for_params(booleantest: false)).to eq [ { booleantest: false } ]
end
it "should work with nil" do
expect(helper.fields_for_params(a: nil)).to eq [ { a: "" } ]
end
it "should raise an error with an unsupported type" do
expect { helper.fields_for_params(a: 1) }.to raise_error(TypeError, "Cannot convert Integer value: 1")
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/locales/i18n_spec.rb | spec/locales/i18n_spec.rb | # frozen_string_literal: true
require "i18n/tasks"
require "i18n-spec"
Dir.glob("config/locales/*.yml") do |locale_file|
RSpec.describe locale_file do
it { is_expected.to be_parseable }
it { is_expected.to have_one_top_level_namespace }
it { is_expected.to be_named_like_top_level_namespace }
it { is_expected.to_not have_legacy_interpolations }
it { is_expected.to have_a_valid_locale }
it { is_expected.to be_a_subset_of "config/locales/en.yml" }
end
end
RSpec.describe "I18n" do
let(:i18n) { I18n::Tasks::BaseTask.new }
let(:unused_keys) { i18n.unused_keys }
let(:unused_key_count) { unused_keys.leaves.count }
let(:unused_key_failure_msg) do
"#{unused_key_count} unused i18n keys, run `bin/i18n-tasks unused` to show them"
end
let(:inconsistent_interpolations) { i18n.inconsistent_interpolations }
let(:inconsistent_interpolation_key_count) { inconsistent_interpolations.leaves.count }
let(:inconsistent_interpolation_failure_msg) do
"#{inconsistent_interpolation_key_count} inconsistent interpolations, run `bin/i18n-tasks check-consistent-interpolations` to show them"
end
let(:non_normalized_paths) { i18n.non_normalized_paths }
let(:non_normalized_paths_count) { non_normalized_paths.size }
let(:non_normalized_paths_failure_msg) do
"#{non_normalized_paths_count} non-normalized paths, run `bin/i18n-tasks check-normalized` to show them"
end
it "does not have unused keys" do
expect(unused_keys).to be_empty, unused_key_failure_msg
end
it "does not have inconsistent interpolations" do
expect(inconsistent_interpolations).to be_empty, inconsistent_interpolation_failure_msg
end
it "does not have non-normalized paths" do
expect(non_normalized_paths).to be_empty, non_normalized_paths_failure_msg
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/page_spec.rb | spec/unit/page_spec.rb | # frozen_string_literal: true
require "rails_helper"
require File.expand_path("config_shared_examples", __dir__)
module ActiveAdmin
RSpec.describe Page do
it_should_behave_like "ActiveAdmin::Resource"
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { Namespace.new(application, :admin) }
let(:page_name) { "Chocolate I lØve You!" }
def config(options = {})
@config ||= namespace.register_page("Chocolate I lØve You!", options)
end
describe "controller name" do
it "should return a namespaced controller name" do
expect(config.controller_name).to eq "Admin::ChocolateILoveYouController"
end
context "when non namespaced controller" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :root) }
it "should return a non namespaced controller name" do
expect(config.controller_name).to eq "ChocolateILoveYouController"
end
end
end
describe "#resource_name" do
it "returns the name" do
expect(config.resource_name).to eq "Chocolate I lØve You!"
end
it "returns the singular, lowercase name" do
expect(config.resource_name.singular).to eq "chocolate i løve you!"
end
end
describe "#plural_resource_label" do
it "returns the singular name" do
expect(config.plural_resource_label).to eq "Chocolate I lØve You!"
end
end
describe "#underscored_resource_name" do
it "returns the resource name underscored" do
expect(config.underscored_resource_name).to eq "chocolate_i_love_you"
end
end
describe "#camelized_resource_name" do
it "returns the resource name camel case" do
expect(config.camelized_resource_name).to eq "ChocolateILoveYou"
end
end
describe "#namespace_name" do
it "returns the name of the namespace" do
expect(config.namespace_name).to eq "admin"
end
end
it "should not belong_to anything" do
expect(config.belongs_to?).to eq false
end
it "should not have any action_items" do
expect(config.action_items?).to eq false
end
it "should not have any sidebar_sections" do
expect(config.sidebar_sections?).to eq false
end
context "with belongs to config" do
let!(:post_config) { namespace.register Post }
let!(:page_config) do
namespace.register_page page_name do
belongs_to :post
end
end
it "configures page with belongs_to" do
expect(page_config.belongs_to?).to be true
end
it "sets navigation menu to parent" do
expect(page_config.navigation_menu_name).to eq :post
end
it "builds a belongs_to relationship" do
belongs_to = page_config.belongs_to_config
expect(belongs_to.target).to eq(post_config)
expect(belongs_to.owner).to eq(page_config)
expect(belongs_to.optional?).to be_falsy
end
it "forwards belongs_to call to controller" do
options = { optional: true }
expect(page_config.controller).to receive(:belongs_to).with(:post, options)
page_config.belongs_to :post, options
end
end # context "with belongs to config" do
context "with optional belongs to config" do
let!(:post_config) { namespace.register Post }
let!(:page_config) do
namespace.register_page page_name do
belongs_to :post, optional: true
end
end
it "does not override default navigation menu" do
expect(page_config.navigation_menu_name).to eq(:default)
end
end # context "with optional belongs to config" do
it "has no belongs_to by default" do
expect(config.belongs_to?).to be_falsy
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/order_clause_spec.rb | spec/unit/order_clause_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::OrderClause do
subject { described_class.new(config, clause) }
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:config) { ActiveAdmin::Resource.new namespace, Post }
describe "id_asc (existing column)" do
let(:clause) { "id_asc" }
it { is_expected.to be_valid }
describe "#field" do
subject { super().field }
it { is_expected.to eq("id") }
end
describe "#order" do
subject { super().order }
it { is_expected.to eq("asc") }
end
specify "#to_sql prepends table name" do
expect(subject.to_sql).to eq '"posts"."id" asc'
end
end
describe "posts.id_asc" do
let(:clause) { "posts.id_asc" }
describe "#table_column" do
subject { super().table_column }
it { is_expected.to eq("posts.id") }
end
end
describe "virtual_column_asc" do
let(:clause) { "virtual_column_asc" }
it { is_expected.to be_valid }
describe "#field" do
subject { super().field }
it { is_expected.to eq("virtual_column") }
end
describe "#order" do
subject { super().order }
it { is_expected.to eq("asc") }
end
specify "#to_sql" do
expect(subject.to_sql).to eq '"virtual_column" asc'
end
end
describe "hstore_col->'field'_desc" do
let(:clause) { "hstore_col->'field'_desc" }
it { is_expected.to be_valid }
describe "#field" do
subject { super().field }
it { is_expected.to eq("hstore_col->'field'") }
end
describe "#order" do
subject { super().order }
it { is_expected.to eq("desc") }
end
it "converts to sql" do
expect(subject.to_sql).to eq %Q("hstore_col"->'field' desc)
end
end
describe "_asc" do
let(:clause) { "_asc" }
it { is_expected.not_to be_valid }
end
describe "nil" do
let(:clause) { nil }
it { is_expected.not_to be_valid }
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/routing_spec.rb | spec/unit/routing_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Routing", type: :routing do
let(:namespaces) { ActiveAdmin.application.namespaces }
it "should only have the namespaces necessary for route testing" do
expect(namespaces.names).to eq [:admin]
end
describe "admin dashboard" do
around do |example|
with_resources_during(example) {}
end
it "should route to the admin dashboard" do
expect(get("/admin")).to route_to "admin/dashboard#index"
end
end
describe "root path helper" do
around do |example|
with_resources_during(example) {}
end
context "when in admin namespace" do
it "should be admin_root_path" do
expect(admin_root_path).to eq "/admin"
end
end
end
describe "route_options" do
around do |example|
with_resources_during(example) { ActiveAdmin.register(Post) }
end
context "with a custom path set in route_options" do
before do
namespaces[:admin].route_options = { path: "/custom-path" }
reload_routes!
end
after do
namespaces[:admin].route_options = {}
reload_routes!
end
it "should route using the custom path" do
expect(admin_posts_path).to eq "/custom-path/posts"
end
end
end
describe "standard resources" do
around do |example|
with_resources_during(example) { ActiveAdmin.register(Post) }
end
context "when in admin namespace" do
it "should route the index path" do
expect(admin_posts_path).to eq "/admin/posts"
end
it "should route the show path" do
expect(admin_post_path(1)).to eq "/admin/posts/1"
end
it "should route the new path" do
expect(new_admin_post_path).to eq "/admin/posts/new"
end
it "should route the edit path" do
expect(edit_admin_post_path(1)).to eq "/admin/posts/1/edit"
end
end
context "when in root namespace" do
around do |example|
with_resources_during(example) { ActiveAdmin.register(Post, namespace: false) }
end
after do
namespaces.instance_variable_get(:@namespaces).delete(:root)
end
it "should route the index path" do
expect(posts_path).to eq "/posts"
end
it "should route the show path" do
expect(post_path(1)).to eq "/posts/1"
end
it "should route the new path" do
expect(new_post_path).to eq "/posts/new"
end
it "should route the edit path" do
expect(edit_post_path(1)).to eq "/posts/1/edit"
end
end
context "with member action" do
context "without an http verb" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(Post) { member_action "do_something" }
end
end
it "should default to GET" do
expect({ get: "/admin/posts/1/do_something" }).to be_routable
expect({ post: "/admin/posts/1/do_something" }).to_not be_routable
end
end
context "with one http verb" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(Post) { member_action "do_something", method: :post }
end
end
it "should properly route" do
expect({ post: "/admin/posts/1/do_something" }).to be_routable
end
end
context "with two http verbs" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(Post) { member_action "do_something", method: [:put, :delete] }
end
end
it "should properly route the first verb" do
expect({ put: "/admin/posts/1/do_something" }).to be_routable
end
it "should properly route the second verb" do
expect({ delete: "/admin/posts/1/do_something" }).to be_routable
end
end
end
end
describe "belongs to resource" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(User)
ActiveAdmin.register(Post) { belongs_to :user, optional: true }
end
end
it "should route the nested index path" do
expect(admin_user_posts_path(1)).to eq "/admin/users/1/posts"
end
it "should route the nested show path" do
expect(admin_user_post_path(1, 2)).to eq "/admin/users/1/posts/2"
end
it "should route the nested new path" do
expect(new_admin_user_post_path(1)).to eq "/admin/users/1/posts/new"
end
it "should route the nested edit path" do
expect(edit_admin_user_post_path(1, 2)).to eq "/admin/users/1/posts/2/edit"
end
context "with collection action" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(Post) do
belongs_to :user, optional: true
end
ActiveAdmin.register(User) do
collection_action "do_something"
end
end
end
it "should properly route the collection action" do
expect({ get: "/admin/users/do_something" }).to \
route_to({ controller: "admin/users", action: "do_something" })
end
end
end
describe "page" do
context "when default namespace" do
around do |example|
with_resources_during(example) { ActiveAdmin.register_page("Chocolate I lØve You!") }
end
it "should route to the page under /admin" do
expect(admin_chocolate_i_love_you_path).to eq "/admin/chocolate_i_love_you"
end
end
context "when in the root namespace" do
around do |example|
with_resources_during(example) { ActiveAdmin.register_page("Chocolate I lØve You!", namespace: false) }
end
after do
namespaces.instance_variable_get(:@namespaces).delete(:root)
end
it "should route to page under /" do
expect(chocolate_i_love_you_path).to eq "/chocolate_i_love_you"
end
end
context "when singular page name" do
around do |example|
with_resources_during(example) { ActiveAdmin.register_page("Log") }
end
it "should not inject _index_ into the route name" do
expect(admin_log_path).to eq "/admin/log"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/menu_collection_spec.rb | spec/unit/menu_collection_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::MenuCollection do
let(:menus) { ActiveAdmin::MenuCollection.new }
describe "#add" do
it "should initialize a new menu when first item" do
menus.add :default, label: "Hello World"
expect(menus.fetch(:default).items.size).to eq 1
expect(menus.fetch(:default)["Hello World"]).to be_an_instance_of(ActiveAdmin::MenuItem)
end
it "should add items to an existing menu" do
menus.add :default, label: "Hello World"
menus.add :default, label: "Hello World Again"
expect(menus.fetch(:default).items.size).to eq 2
end
end
describe "#clear!" do
it "should remove all menus" do
menus.add :default, label: "Hello World"
menus.clear!
expect do
menus.fetch(:non_default_menu)
end.to raise_error(ActiveAdmin::NoMenuError)
end
end
describe "#on_build" do
it "runs a callback when fetching a menu" do
menus.on_build do |m|
m.add :default, label: "Hello World"
end
expect(menus.fetch(:default)["Hello World"]).to_not eq nil
end
it "re-runs the callbacks when the menu is cleared" do
menus.on_build do |m|
m.add :default, label: "Hello World"
end
expect(menus.fetch(:default)["Hello World"]).to_not eq nil
menus.clear!
expect(menus.fetch(:default)["Hello World"]).to_not eq nil
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/settings_node_spec.rb | spec/unit/settings_node_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::SettingsNode do
subject { ActiveAdmin::SettingsNode.build }
let!(:child) { ActiveAdmin::SettingsNode.build(subject) }
context "parent setting includes foo" do
before { subject.register :foo, true }
it "returns parent settings" do
expect(child.foo).to eq true
end
it "fails if setting undefined" do
expect do
child.bar
end.to raise_error(NoMethodError)
end
context "child overrides foo" do
before { child.foo = false }
it { expect(child.foo).to eq false }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/dependency_spec.rb | spec/unit/dependency_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Dependency do
describe "method_missing" do
before do
allow(Gem).to receive(:loaded_specs)
.and_return "foo" => Gem::Specification.new("foo", "1.2.3")
end
it "returns a Matcher" do
expect(described_class.foo).to be_a ActiveAdmin::Dependency::Matcher
expect(described_class.foo.inspect).to eq "<ActiveAdmin::Dependency::Matcher for foo 1.2.3>"
expect(described_class.bar.inspect).to eq "<ActiveAdmin::Dependency::Matcher for (missing)>"
end
describe "`?`" do
it "base" do
expect(described_class.foo?).to eq true
expect(described_class.bar?).to eq false
end
it "=" do
expect(described_class.foo? "= 1.2.3").to eq true
expect(described_class.foo? "= 1").to eq false
end
it ">" do
expect(described_class.foo? "> 1").to eq true
expect(described_class.foo? "> 2").to eq false
end
it "<" do
expect(described_class.foo? "< 2").to eq true
expect(described_class.foo? "< 1").to eq false
end
it ">=" do
expect(described_class.foo? ">= 1.2.3").to eq true
expect(described_class.foo? ">= 1.2.2").to eq true
expect(described_class.foo? ">= 1.2.4").to eq false
end
it "<=" do
expect(described_class.foo? "<= 1.2.3").to eq true
expect(described_class.foo? "<= 1.2.4").to eq true
expect(described_class.foo? "<= 1.2.2").to eq false
end
it "~>" do
expect(described_class.foo? "~> 1.2.0").to eq true
expect(described_class.foo? "~> 1.1").to eq true
expect(described_class.foo? "~> 1.2.4").to eq false
end
end
describe "`!`" do
it "raises an error if requirement not met" do
expect { described_class.foo! "5" }
.to raise_error(ActiveAdmin::DependencyError, "You provided foo 1.2.3 but we need: 5.")
end
it "accepts multiple arguments" do
expect { described_class.foo! "> 1", "< 1.2" }
.to raise_error(ActiveAdmin::DependencyError, "You provided foo 1.2.3 but we need: > 1, < 1.2.")
end
it "raises an error if not provided" do
expect { described_class.bar! }
.to raise_error(ActiveAdmin::DependencyError, "To use bar you need to specify it in your Gemfile.")
end
end
end
describe "[]" do
before do
allow(Gem).to receive(:loaded_specs)
.and_return "a-b" => Gem::Specification.new("a-b", "1.2.3")
end
it "allows access to gems with an arbitrary name" do
expect(described_class["a-b"]).to be_a ActiveAdmin::Dependency::Matcher
expect(described_class["a-b"].inspect).to eq "<ActiveAdmin::Dependency::Matcher for a-b 1.2.3>"
expect(described_class["c-d"].inspect).to eq "<ActiveAdmin::Dependency::Matcher for (missing)>"
end
# Note: more extensive tests for match? and match! are above.
it "match?" do
expect(described_class["a-b"].match?).to eq true
expect(described_class["a-b"].match? "1.2.3").to eq true
expect(described_class["b-c"].match?).to eq false
end
it "match!" do
expect(described_class["a-b"].match!).to eq nil
expect(described_class["a-b"].match! "1.2.3").to eq nil
expect { described_class["a-b"].match! "2.5" }
.to raise_error(ActiveAdmin::DependencyError, "You provided a-b 1.2.3 but we need: 2.5.")
expect { described_class["b-c"].match! }
.to raise_error(ActiveAdmin::DependencyError, "To use b-c you need to specify it in your Gemfile.")
end
# Note: Ruby comparison operators are separate from the `foo? '> 1'` syntax
describe "Ruby comparison syntax" do
it "==" do
expect(described_class["a-b"] == "1.2.3").to eq true
expect(described_class["a-b"] == "1.2").to eq false
expect(described_class["a-b"] == 1).to eq false
end
it ">" do
expect(described_class["a-b"] > 1).to eq true
expect(described_class["a-b"] > 2).to eq false
end
it "<" do
expect(described_class["a-b"] < 2).to eq true
expect(described_class["a-b"] < 1).to eq false
end
it ">=" do
expect(described_class["a-b"] >= "1.2.3").to eq true
expect(described_class["a-b"] >= "1.2.2").to eq true
expect(described_class["a-b"] >= "1.2.4").to eq false
end
it "<=" do
expect(described_class["a-b"] <= "1.2.3").to eq true
expect(described_class["a-b"] <= "1.2.4").to eq true
expect(described_class["a-b"] <= "1.2.2").to eq false
end
it "throws a custom error if the gem is missing" do
expect { described_class["b-c"] < 23 }
.to raise_error(ActiveAdmin::DependencyError, "To use b-c you need to specify it in your Gemfile.")
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_collection_spec.rb | spec/unit/resource_collection_spec.rb | # frozen_string_literal: true
require "rails_helper"
require "active_admin/resource_collection"
RSpec.describe ActiveAdmin::ResourceCollection do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:collection) { ActiveAdmin::ResourceCollection.new }
let(:resource) { double resource_name: "MyResource" }
it { is_expected.to respond_to :[] }
it { is_expected.to respond_to :add }
it { is_expected.to respond_to :each }
it { is_expected.to respond_to :has_key? }
it { is_expected.to respond_to :keys }
it { is_expected.to respond_to :values }
it { is_expected.to respond_to :size }
it { is_expected.to respond_to :to_a }
it "should have no resources when new" do
expect(collection).to be_empty
end
it "should be enumerable" do
collection.add(resource)
collection.each { |r| expect(r).to eq resource }
end
it "should return the available keys" do
collection.add resource
expect(collection.keys).to eq [resource.resource_name]
end
describe "#add" do
it "should return the resource" do
expect(collection.add(resource)).to eq resource
end
it "should add a new resource" do
collection.add(resource)
expect(collection.values).to eq [resource]
end
it "should be available by name" do
collection.add(resource)
expect(collection[resource.resource_name]).to eq resource
end
it "shouldn't happen twice" do
collection.add(resource); collection.add(resource)
expect(collection.values).to eq [resource]
end
it "shouldn't allow a resource name mismatch to occur" do
expect do
ActiveAdmin.register Category
ActiveAdmin.register Post, as: "Category"
end.to raise_error ActiveAdmin::ResourceCollection::ConfigMismatch
end
it "shouldn't allow a Page/Resource mismatch to occur" do
expect do
ActiveAdmin.register User
ActiveAdmin.register_page "User"
end.to raise_error ActiveAdmin::ResourceCollection::IncorrectClass
end
describe "should store both renamed and non-renamed resources" do
let(:resource) { ActiveAdmin::Resource.new namespace, Category }
let(:renamed) { ActiveAdmin::Resource.new namespace, Category, as: "Subcategory" }
it "when the renamed version is added first" do
collection.add renamed
collection.add resource
expect(collection.values).to include(resource, renamed)
end
it "when the renamed version is added last" do
collection.add resource
collection.add renamed
expect(collection.values).to include(resource, renamed)
end
end
end
describe "#[]" do
let(:resource) { ActiveAdmin::Resource.new namespace, resource_class }
let(:inherited_resource) { ActiveAdmin::Resource.new namespace, inherited_resource_class }
let(:resource_class) { User }
let(:inherited_resource_class) { Publisher }
let(:unregistered_class) { Category }
context "with resources" do
before do
collection.add resource
collection.add inherited_resource
end
it "should find resource by class" do
expect(collection[resource_class]).to eq resource
end
it "should find resource by class string" do
expect(collection[resource_class.to_s]).to eq resource
end
it "should find inherited resource by class" do
expect(collection[inherited_resource_class]).to eq inherited_resource
end
it "should find inherited resource by class string" do
expect(collection[inherited_resource_class.to_s]).to eq inherited_resource
end
it "should return nil when the resource_class does not respond to base_class and it is not in the collection" do
expect(collection[double]).to eq nil
end
it "should return nil when a resource class is NOT in the collection" do
expect(collection[unregistered_class]).to eq nil
end
end
context "without inherited resources" do
before do
collection.add resource
end
it "should find resource by inherited class" do
expect(collection[inherited_resource_class]).to eq resource
end
end
context "with a renamed resource" do
let(:renamed_resource) { ActiveAdmin::Resource.new namespace, resource_class, as: name }
let(:name) { "Administrators" }
before do
collection.add renamed_resource
end
it "should find resource by class" do
expect(collection[resource_class]).to eq renamed_resource
end
it "should find resource by class string" do
expect(collection[resource_class.to_s]).to eq renamed_resource
end
it "should find resource by name" do
expect(collection[name]).to eq renamed_resource
end
end
context "with a resource and a renamed resource added in disorder" do
let(:resource) { ActiveAdmin::Resource.new namespace, resource_class }
let(:renamed_resource) do
ActiveAdmin::Resource.new namespace, resource_class, as: name
end
let(:name) { "Administrators" }
before do
collection.add renamed_resource
collection.add resource
end
it "should find a resource by class when there are two resources with that class" do
expect(collection[resource_class]).to eq resource
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/devise_spec.rb | spec/unit/devise_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Devise::Controller do
let(:controller_class) do
klass = Class.new do
def self.layout(*); end
def self.helper(*); end
end
klass.send(:include, ActiveAdmin::Devise::Controller)
klass
end
let(:controller) { controller_class.new }
let(:action_controller_config) { Rails.configuration.action_controller }
def with_temp_relative_url_root(relative_url_root)
previous_relative_url_root = action_controller_config[:relative_url_root]
action_controller_config[:relative_url_root] = relative_url_root
yield
ensure
action_controller_config[:relative_url_root] = previous_relative_url_root
end
context "with a RAILS_RELATIVE_URL_ROOT set" do
around do |example|
with_temp_relative_url_root("/foo") { example.call }
end
it "should set the root path to the default namespace" do
expect(controller.root_path).to eq "/foo/admin"
end
it "should set the root path to '/' when no default namespace" do
allow(ActiveAdmin.application).to receive(:default_namespace).and_return(false)
expect(controller.root_path).to eq "/foo/"
end
end
context "without a RAILS_RELATIVE_URL_ROOT set" do
around do |example|
with_temp_relative_url_root(nil) { example.call }
end
it "should set the root path to the default namespace" do
expect(controller.root_path).to eq "/admin"
end
it "should set the root path to '/' when no default namespace" do
allow(ActiveAdmin.application).to receive(:default_namespace).and_return(false)
expect(controller.root_path).to eq "/"
end
end
context "within a scoped route" do
SCOPE = "/aa_scoped"
before do
# Remove existing routes
routes = Rails.application.routes
routes.clear!
# Add scoped routes
routes.draw do
scope path: SCOPE do
ActiveAdmin.routes(self)
devise_for :admin_users, ActiveAdmin::Devise.config
end
end
end
after do
# Resume default routes
reload_routes!
end
it "should include scope path in root_path" do
expect(controller.root_path).to eq "#{SCOPE}/admin"
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/active_admin_spec.rb | spec/unit/active_admin_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin do
%w(register register_page unload! load! routes).each do |method|
it "delegates ##{method} to application" do
expect(ActiveAdmin.application).to receive(method)
ActiveAdmin.send(method)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/dsl_spec.rb | spec/unit/dsl_spec.rb | # frozen_string_literal: true
require "rails_helper"
module MockModuleToInclude
def self.included(dsl)
end
end
RSpec.describe ActiveAdmin::DSL do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { namespace.register Post }
let(:dsl) { ActiveAdmin::DSL.new(resource_config) }
describe "#include" do
it "should call the included class method on the module that is included" do
expect(MockModuleToInclude).to receive(:included).with(dsl)
dsl.run_registration_block do
include MockModuleToInclude
end
end
end
describe "#action_item" do
before do
@default_items_count = resource_config.action_items.size
dsl.run_registration_block do
action_item :awesome, only: :show do
"Awesome ActionItem"
end
end
end
it "adds action_item to the action_items of config" do
expect(resource_config.action_items.size).to eq(@default_items_count + 1)
end
end
describe "#menu" do
it "should set the menu_item_options on the configuration" do
expect(resource_config).to receive(:menu_item_options=).with({ parent: "Admin" })
dsl.run_registration_block do
menu parent: "Admin"
end
end
end
describe "#navigation_menu" do
it "should set the navigation_menu_name on the configuration" do
expect(resource_config).to receive(:navigation_menu_name=).with(:admin)
dsl.run_registration_block do
navigation_menu :admin
end
end
it "should accept a block" do
dsl = ActiveAdmin::DSL.new(resource_config)
dsl.run_registration_block do
navigation_menu { :dynamic_menu }
end
expect(resource_config.navigation_menu_name).to eq :dynamic_menu
end
end
describe "#sidebar" do
before do
dsl.config.sidebar_sections << ActiveAdmin::SidebarSection.new(:email)
end
it "add sidebar_section to the sidebar_sections of config" do
dsl.run_registration_block do
sidebar :help
end
expect(dsl.config.sidebar_sections.map(&:name)).to match_array ["filters", "active_search", "email", "help"]
end
end
describe "#batch_action" do
it "should add a batch action by symbol" do
dsl.run_registration_block do
config.batch_actions = true
batch_action :foo
end
expect(resource_config.batch_actions.map(&:sym)).to eq [:foo, :destroy]
end
it "should add a batch action by title" do
dsl.run_registration_block do
config.batch_actions = true
batch_action "foo bar"
end
expect(resource_config.batch_actions.map(&:sym)).to eq [:foo_bar, :destroy]
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/menu_item_spec.rb | spec/unit/menu_item_spec.rb | # frozen_string_literal: true
require "rails_helper"
require "active_admin/menu"
require "active_admin/menu_item"
module ActiveAdmin
RSpec.describe MenuItem do
it "should have a label" do
item = MenuItem.new(label: "Dashboard")
expect(item.label).to eq "Dashboard"
end
it "should have a url" do
item = MenuItem.new(url: "/admin")
expect(item.url).to eq "/admin"
end
it "should have a priority of 10 by default" do
item = MenuItem.new
expect(item.priority).to eq 10
end
it "should default to an empty hash for html_options" do
item = MenuItem.new
expect(item.html_options).to be_empty
end
it "should accept an options hash for link_to" do
item = MenuItem.new html_options: { target: "_blank" }
expect(item.html_options).to include(target: "_blank")
end
context "with no items" do
it "should be empty" do
item = MenuItem.new
expect(item.items).to be_empty
end
it "should accept new children" do
item = MenuItem.new label: "Dashboard"
item.add label: "My Child Dashboard"
expect(item.items.first).to be_a MenuItem
expect(item.items.first.label).to eq "My Child Dashboard"
end
end
context "with many children" do
let(:item) do
i = MenuItem.new(label: "Dashboard")
i.add label: "Blog"
i.add label: "Cars"
i.add label: "Users", priority: 1
i.add label: "Settings", priority: 2
i.add label: "Analytics", priority: 44
i
end
it "should contain 5 submenu items" do
expect(item.items.count).to eq 5
end
it "should give access to the menu item as an array" do
expect(item["Blog"].label).to eq "Blog"
end
it "children should hold a reference to their parent" do
expect(item["Blog"].parent).to eq item
end
end
describe "#id" do
it "should be normalized" do
expect(MenuItem.new(id: "Foo Bar").id).to eq "foo_bar"
end
it "should not accept Procs" do
expect { MenuItem.new(id: proc { "Dynamic" }).id }.to raise_error TypeError
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_registration_spec.rb | spec/unit/resource_registration_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Registering an object to administer" do
let(:application) { ActiveAdmin::Application.new }
context "with no configuration" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
before do
application.namespaces[namespace.name] = namespace
end
it "should call register on the namespace" do
expect(namespace).to receive(:register)
application.register Category
end
it "should dispatch a Resource::RegisterEvent" do
expect(ActiveSupport::Notifications).to(
receive(:instrument)
.with(
ActiveAdmin::Resource::RegisterEvent,
hash_including(active_admin_resource: an_instance_of(ActiveAdmin::Resource))
)
)
application.register Category
end
end
context "with a different namespace" do
it "should call register on the namespace" do
namespace = ActiveAdmin::Namespace.new(application, :hello_world)
application.namespaces[namespace.name] = namespace
expect(namespace).to receive(:register)
application.register Category, namespace: :hello_world
end
it "should generate a Namespace::RegisterEvent and a Resource::RegisterEvent" do
expect(ActiveSupport::Notifications).to(
receive(:instrument)
.with(
ActiveAdmin::Namespace::RegisterEvent,
hash_including(active_admin_namespace: an_instance_of(ActiveAdmin::Namespace))
)
)
expect(ActiveSupport::Notifications).to(
receive(:instrument)
.with(
ActiveAdmin::Resource::RegisterEvent,
hash_including(active_admin_resource: an_instance_of(ActiveAdmin::Resource))
)
)
application.register Category, namespace: :not_yet_created
end
end
context "with no namespace" do
it "should call register on the root namespace" do
namespace = ActiveAdmin::Namespace.new(application, :root)
application.namespaces[namespace.name] = namespace
expect(namespace).to receive(:register)
application.register Category, namespace: false
end
end
context "when being registered multiple times" do
it "should run the dsl in the same config object" do
config_1 = ActiveAdmin.register(Category) { filter :name }
config_2 = ActiveAdmin.register(Category) { filter :id }
expect(config_1).to eq config_2
expect(config_1.filters.size).to eq 2
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/scope_spec.rb | spec/unit/scope_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Scope do
describe "creating a scope" do
subject { scope }
context "when just a scope method" do
let(:scope) { ActiveAdmin::Scope.new :published }
describe "#name" do
subject { super().name }
it { is_expected.to eq("Published") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("published") }
end
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq(:published) }
end
end
context "when scope method is :all" do
let(:scope) { ActiveAdmin::Scope.new :all }
describe "#name" do
subject { super().name }
it { is_expected.to eq("All") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("all") }
end
# :all does not return a chain but an array of active record
# instances. We set the scope_method to nil then.
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq(nil) }
end
describe "#scope_block" do
subject { super().scope_block }
it { is_expected.to eq(nil) }
end
end
context "when a name and scope method is :all" do
let(:scope) { ActiveAdmin::Scope.new "Tous", :all }
describe "#name" do
subject { super().name }
it { is_expected.to eq "Tous" }
end
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq nil }
end
describe "#scope_block" do
subject { super().scope_block }
it { is_expected.to eq nil }
end
end
context "when a name and scope method" do
let(:scope) { ActiveAdmin::Scope.new "With API Access", :with_api_access }
describe "#name" do
subject { super().name }
it { is_expected.to eq("With API Access") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("with_api_access") }
end
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq(:with_api_access) }
end
end
context "when a name and scope block" do
let(:scope) { ActiveAdmin::Scope.new("My Scope") { |s| s } }
describe "#name" do
subject { super().name }
it { is_expected.to eq("My Scope") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("my_scope") }
end
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq(nil) }
end
describe "#scope_block" do
subject { super().scope_block }
it { is_expected.to be_a(Proc) }
end
end
context "when a name has a space and lowercase" do
let(:scope) { ActiveAdmin::Scope.new("my scope") }
describe "#name" do
subject { super().name }
it { is_expected.to eq("my scope") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("my_scope") }
end
end
context "with a proc as the label" do
it "should raise an exception if a second argument isn't provided" do
expect do
ActiveAdmin::Scope.new proc { Date.today.strftime "%A" }
end.to raise_error "A string/symbol is required as the second argument if your label is a proc."
end
it "should properly render the proc" do
scope = ActiveAdmin::Scope.new proc { Date.today.strftime "%A" }, :foobar
expect(scope.name.call).to eq Date.today.strftime "%A"
end
end
context "with scope method and localizer" do
let(:localizer) do
loc = double(:localizer)
allow(loc).to receive(:t).with(:published, scope: "scopes").and_return("All published")
loc
end
let(:scope) { ActiveAdmin::Scope.new :published, :published, localizer: localizer }
describe "#name" do
subject { super().name }
it { is_expected.to eq("All published") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq("published") }
end
describe "#scope_method" do
subject { super().scope_method }
it { is_expected.to eq(:published) }
end
end
end # describe "creating a scope"
describe "#display_if_block" do
it "should return true by default" do
scope = ActiveAdmin::Scope.new(:default)
expect(scope.display_if_block.call).to eq true
end
it "should return the :if block if set" do
scope = ActiveAdmin::Scope.new(:with_block, nil, if: proc { false })
expect(scope.display_if_block.call).to eq false
end
end
describe "#default" do
it "should accept a boolean" do
scope = ActiveAdmin::Scope.new(:method, nil, default: true)
expect(scope.default_block).to eq true
end
it "should default to a false #default_block" do
scope = ActiveAdmin::Scope.new(:method, nil)
expect(scope.default_block.call).to eq false
end
it "should store the :default proc" do
scope = ActiveAdmin::Scope.new(:with_block, nil, default: proc { true })
expect(scope.default_block.call).to eq true
end
end
describe "show_count" do
it "should allow setting of show_count to prevent showing counts" do
scope = ActiveAdmin::Scope.new(:default, nil, show_count: false)
expect(scope.show_count).to eq false
end
it "should allow setting of show_count to query counts asynchronously" do
scope = ActiveAdmin::Scope.new(:default, nil, show_count: :async)
expect(scope.show_count).to eq :async
end
it "should set show_count to true if not passed in" do
scope = ActiveAdmin::Scope.new(:default)
expect(scope.show_count).to eq true
end
end
describe "#async_count?" do
it "should return true when show_count is :async" do
scope = ActiveAdmin::Scope.new(:default, nil, show_count: :async)
expect(scope.async_count?).to eq true
end
it "should return false show_count is not passed in" do
scope = ActiveAdmin::Scope.new(:default)
expect(scope.async_count?).to eq false
end
it "should return false when show_count is false" do
scope = ActiveAdmin::Scope.new(:default, nil, show_count: false)
expect(scope.async_count?).to eq false
end
end
describe "group" do
it "should default to nil" do
scope = ActiveAdmin::Scope.new(:default)
expect(scope.group).to eq nil
end
it "should accept a symbol to assign a group to the scope" do
scope = ActiveAdmin::Scope.new(:default, nil, group: :test)
expect(scope.group).to eq :test
end
it "should accept a string to assign a group to the scope" do
scope = ActiveAdmin::Scope.new(:default, nil, group: "test")
expect(scope.group).to eq :test
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/controller_filters_spec.rb | spec/unit/controller_filters_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Application do
let(:application) { ActiveAdmin::Application.new }
let(:controllers) { application.controllers_for_filters }
it "controllers_for_filters" do
expect(application.controllers_for_filters).to eq [
ActiveAdmin::BaseController, ActiveAdmin::Devise::SessionsController,
ActiveAdmin::Devise::PasswordsController, ActiveAdmin::Devise::UnlocksController,
ActiveAdmin::Devise::RegistrationsController, ActiveAdmin::Devise::ConfirmationsController
]
end
%w[
skip_before_action skip_around_action skip_after_action
append_before_action append_around_action append_after_action
prepend_before_action prepend_around_action prepend_after_action
before_action around_action after_action
].each do |filter|
it filter do
args = [:my_filter, { only: :show }]
controllers.each { |c| expect(c).to receive(filter).with(args) }
application.public_send filter, args
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/action_builder_spec.rb | spec/unit/action_builder_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "defining actions from registration blocks", type: :controller do
let(:klass) { Admin::PostsController }
before do
load_resources { action! }
@controller = klass.new
end
describe "creates a member action" do
after do
klass.clear_member_actions!
end
context "with a block" do
let(:action!) do
ActiveAdmin.register Post do
member_action :comment do
# Do nothing
end
end
end
it "should create a new public instance method" do
expect(klass.public_instance_methods.collect(&:to_s)).to include("comment")
end
it "should add itself to the member actions config" do
expect(klass.active_admin_config.member_actions.size).to eq 1
end
it "should create a new named route" do
expect(Rails.application.routes.url_helpers.methods.collect(&:to_s)).to include("comment_admin_post_path")
end
end
context "without a block" do
let(:action!) do
ActiveAdmin.register Post do
member_action :comment
end
end
it "should still generate a new empty action" do
expect(klass.public_instance_methods.collect(&:to_s)).to include("comment")
end
end
context "with :title" do
let(:action!) do
ActiveAdmin.register Post do
member_action :comment, title: "My Awesome Comment" do
render json: { a: 2 }
end
end
end
it "sets the page title" do
get :comment, params: { id: 1 }
expect(controller.instance_variable_get(:@page_title)).to eq "My Awesome Comment"
end
end
end
describe "creates a collection action" do
after do
klass.clear_collection_actions!
end
context "with a block" do
let(:action!) do
ActiveAdmin.register Post do
collection_action :comments do
# Do nothing
end
end
end
it "should create a public instance method" do
expect(klass.public_instance_methods.collect(&:to_s)).to include("comments")
end
it "should add itself to the member actions config" do
expect(klass.active_admin_config.collection_actions.size).to eq 1
end
it "should create a named route" do
expect(Rails.application.routes.url_helpers.methods.collect(&:to_s)).to include("comments_admin_posts_path")
end
end
context "without a block" do
let(:action!) do
ActiveAdmin.register Post do
collection_action :comments
end
end
it "should still generate a new empty action" do
expect(klass.public_instance_methods.collect(&:to_s)).to include("comments")
end
end
context "with :title" do
let(:action!) do
ActiveAdmin.register Post do
collection_action :comments, title: "My Awesome Comments" do
render json: { a: 2 }
end
end
end
it "sets the page title" do
get :comments
expect(controller.instance_variable_get(:@page_title)).to eq "My Awesome Comments"
end
end
end
context "when method with given name is already defined" do
include_context "capture stderr"
describe "defining member action" do
let :action! do
ActiveAdmin.register Post do
member_action :process
end
end
it "writes warning to $stderr" do
expect($stderr.string).to include("Warning: method `process` already defined in Admin::PostsController")
end
end
describe "defining collection action" do
let :action! do
ActiveAdmin.register Post do
collection_action :process
end
end
it "writes warning to $stderr" do
expect($stderr.string).to include("Warning: method `process` already defined in Admin::PostsController")
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/comments_spec.rb | spec/unit/comments_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Comments" do
let(:application) { ActiveAdmin::Application.new }
describe ActiveAdmin::Comment do
let(:comment) { ActiveAdmin::Comment.new }
let(:user) { User.create!(first_name: "John", last_name: "Doe") }
let(:post) { Post.create!(title: "Hello World") }
it "belongs to a resource" do
comment.assign_attributes(resource_type: "Post", resource_id: post.id)
expect(comment.resource).to eq(post)
end
it "belongs to an author" do
comment.assign_attributes(author_type: "User", author_id: user.id)
expect(comment.author).to eq(user)
end
it "needs a body" do
expect(comment).to_not be_valid
expect(comment.errors[:body]).to eq(["can't be blank"])
end
it "needs a namespace" do
expect(comment).to_not be_valid
expect(comment.errors[:namespace]).to eq(["can't be blank"])
end
it "needs a resource" do
expect(comment).to_not be_valid
expect(comment.errors[:resource]).to eq(["can't be blank"])
end
it "authorizes default ransackable attributes" do
expect(described_class.ransackable_attributes).to eq described_class.authorizable_ransackable_attributes
end
it "authorizes default ransackable associations" do
expect(described_class.ransackable_associations).to eq described_class.authorizable_ransackable_associations
end
describe ".find_for_resource_in_namespace" do
let(:namespace_name) { "admin" }
before do
@comment = ActiveAdmin::Comment.create! author: user,
resource: post,
body: "A Comment",
namespace: namespace_name
end
it "should return a comment for the resource in the same namespace" do
expect(ActiveAdmin::Comment.find_for_resource_in_namespace(post, namespace_name)).to eq [@comment]
end
it "should not return a comment for the same resource in a different namespace" do
ActiveAdmin.application.namespaces[:public] = ActiveAdmin.application.namespaces[:admin]
expect(ActiveAdmin::Comment.find_for_resource_in_namespace(post, "public")).to eq []
ActiveAdmin.application.namespaces.instance_variable_get(:@namespaces).delete(:public)
end
it "should not return a comment for a different resource" do
another_post = Post.create! title: "Another Hello World"
expect(ActiveAdmin::Comment.find_for_resource_in_namespace(another_post, namespace_name)).to eq []
end
it "should return the most recent comment first by default" do
another_comment = ActiveAdmin::Comment.create! author: user,
resource: post,
body: "Another Comment",
namespace: namespace_name,
created_at: @comment.created_at + 20.minutes
yet_another_comment = ActiveAdmin::Comment.create! author: user,
resource: post,
body: "Yet Another Comment",
namespace: namespace_name,
created_at: @comment.created_at + 10.minutes
comments = ActiveAdmin::Comment.find_for_resource_in_namespace(post, namespace_name)
expect(comments.size).to eq 3
expect(comments.first).to eq(@comment)
expect(comments.second).to eq(yet_another_comment)
expect(comments.last).to eq(another_comment)
end
context "when custom ordering configured" do
around do |example|
previous_order = ActiveAdmin.application.comments_order
ActiveAdmin.application.comments_order = "created_at DESC"
example.call
ActiveAdmin.application.comments_order = previous_order
end
it "should return the correctly ordered comments" do
another_comment = ActiveAdmin::Comment.create!(
author: user,
resource: post,
body: "Another Comment",
namespace: namespace_name,
created_at: @comment.created_at + 20.minutes
)
comments = ActiveAdmin::Comment.find_for_resource_in_namespace(
post, namespace_name
)
expect(comments.size).to eq 2
expect(comments.first).to eq(another_comment)
expect(comments.last).to eq(@comment)
end
end
end
describe ".resource_type" do
let(:post) { Post.create!(title: "Testing.") }
let(:post_decorator) { double "PostDecorator" }
before do
allow(post_decorator).to receive(:model).and_return(post)
allow(post_decorator).to receive(:decorated?).and_return(true)
end
context "when a decorated object is passed" do
let(:resource) { post_decorator }
it "returns undeorated object class string" do
expect(ActiveAdmin::Comment.resource_type resource).to eql "Post"
end
end
context "when an undecorated object is passed" do
let(:resource) { post }
it "returns object class string" do
expect(ActiveAdmin::Comment.resource_type resource).to eql "Post"
end
end
end
describe "Commenting on resource with string id" do
let(:tag) { Tag.create!(name: "cooltags") }
let(:namespace_name) { "admin" }
it "should allow commenting" do
comment = ActiveAdmin::Comment.create!(
author: user,
resource: tag,
body: "Another Comment",
namespace: namespace_name)
expect(ActiveAdmin::Comment.find_for_resource_in_namespace(tag, namespace_name)).to eq [comment]
end
end
describe "commenting on child of STI resource" do
let(:publisher) { Publisher.create!(username: "tenderlove") }
let(:namespace_name) { "admin" }
it "should assign child class as commented resource" do
ActiveAdmin::Comment.create!(
author: user,
resource: publisher,
body: "Lorem Ipsum",
namespace: namespace_name)
expect(ActiveAdmin::Comment.find_for_resource_in_namespace(publisher, namespace_name).last.resource_type).
to eq("User")
end
end
end
describe ActiveAdmin::Comments::NamespaceHelper do
describe "#comments?" do
it "should have comments when the namespace allows comments" do
ns = ActiveAdmin::Namespace.new(application, :admin)
ns.comments = true
expect(ns.comments?).to eq true
end
it "should not have comments when the namespace does not allow comments" do
ns = ActiveAdmin::Namespace.new(application, :admin)
ns.comments = false
expect(ns.comments?).to eq false
end
end
end
describe ActiveAdmin::Comments::ResourceHelper do
it "should add an attr_accessor :comments to ActiveAdmin::Resource" do
ns = ActiveAdmin::Namespace.new(application, :admin)
resource = ActiveAdmin::Resource.new(ns, Post)
expect(resource.comments).to eq nil
resource.comments = true
expect(resource.comments).to eq true
end
it "should disable comments if set to false" do
ns = ActiveAdmin::Namespace.new(application, :admin)
resource = ActiveAdmin::Resource.new(ns, Post)
resource.comments = false
expect(resource.comments?).to eq false
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/collection_decorator_spec.rb | spec/unit/collection_decorator_spec.rb | # frozen_string_literal: true
require "rails_helper"
class NumberDecorator
def initialize(number)
@number = number
end
def selectable?
@number.even?
end
end
RSpec.describe ActiveAdmin::CollectionDecorator do
describe "#decorated_collection" do
subject { collection.decorated_collection }
let(:collection) { ActiveAdmin::CollectionDecorator.decorate((1..10).to_a, with: NumberDecorator) }
it "returns an array of decorated objects" do
expect(subject).to all(be_a(NumberDecorator))
end
end
describe "array methods" do
subject { ActiveAdmin::CollectionDecorator.decorate((1..10).to_a, with: NumberDecorator) }
it "delegates them to the decorated collection" do
expect(subject.count(&:selectable?)).to eq(5)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/csv_builder_spec.rb | spec/unit/csv_builder_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::CSVBuilder do
describe ".default_for_resource using Post" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
let(:resource) { ActiveAdmin::Resource.new(namespace, Post, {}) }
let(:csv_builder) { ActiveAdmin::CSVBuilder.default_for_resource(resource).tap(&:exec_columns) }
it "returns a default csv_builder for Post" do
expect(csv_builder).to be_a(ActiveAdmin::CSVBuilder)
end
it "defines Id as the first column" do
expect(csv_builder.columns.first.name).to eq "Id"
expect(csv_builder.columns.first.data).to eq :id
end
it "has Post's content_columns" do
csv_builder.columns[1..-1].each_with_index do |column, index|
expect(column.name).to eq resource.content_columns[index].to_s.humanize
expect(column.data).to eq resource.content_columns[index]
end
end
context "when column has a localized name" do
let(:localized_name) { "Titulo" }
before do
allow(Post).to receive(:human_attribute_name).and_call_original
allow(Post).to receive(:human_attribute_name).with(:title) { localized_name }
end
it "gets name from I18n" do
title_index = resource.content_columns.index(:title) + 1 # First col is always id
expect(csv_builder.columns[title_index].name).to eq localized_name
end
end
context "for models having sensitive attributes" do
let(:resource) { ActiveAdmin::Resource.new(namespace, User, {}) }
it "omits sensitive fields" do
expect(csv_builder.columns.map(&:data)).to_not include :encrypted_password
end
end
end
context "when empty" do
let(:builder) { ActiveAdmin::CSVBuilder.new.tap(&:exec_columns) }
it "should have no columns" do
expect(builder.columns).to eq []
end
end
context "with a symbol column (:title)" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column :title
end.tap(&:exec_columns)
end
it "should have one column" do
expect(builder.columns.size).to eq 1
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'Title'" do
expect(column.name).to eq "Title"
end
it "should have the data :title" do
expect(column.data).to eq :title
end
end
end
context "with a block and title" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "My title" do
# nothing
end
end.tap(&:exec_columns)
end
it "should have one column" do
expect(builder.columns.size).to eq 1
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'My title'" do
expect(column.name).to eq "My title"
end
it "should have the data :title" do
expect(column.data).to be_an_instance_of(Proc)
end
end
end
context "with a humanize_name column option" do
context "with symbol column name" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column :my_title, humanize_name: false
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
context "with string column name" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "my_title", humanize_name: false
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
end
context "with a separator" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(col_sep: ";").tap(&:exec_columns)
end
it "should have proper separator" do
expect(builder.options).to include(col_sep: ";")
end
end
context "with humanize_name option" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(humanize_name: false) do
column :my_title
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have humanize_name option set" do
expect(column.options).to eq humanize_name: false
end
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
context "with csv_options" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(force_quotes: true).tap(&:exec_columns)
end
it "should have proper separator" do
expect(builder.options).to include(force_quotes: true)
end
end
context "with access to the controller" do
let(:dummy_view_context) { double(controller: dummy_controller) }
let(:dummy_controller) { double(names: %w(title summary updated_at created_at)) }
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "id"
controller.names.each do |name|
column(name)
end
end.tap { |b| b.exec_columns(dummy_view_context) }
end
it "should build columns provided by the controller" do
expect(builder.columns.map(&:data)).to match_array([:id, :title, :summary, :updated_at, :created_at])
end
end
context "build csv using the supplied order" do
before do
@post1 = Post.create!(title: "Hello1", published_date: Date.today - 2.day)
@post2 = Post.create!(title: "Hello2", published_date: Date.today - 1.day)
end
let(:dummy_controller) do
class DummyController
def in_paginated_batches(&block)
Post.order("published_date DESC").each(&block)
end
def apply_decorator(resource)
resource
end
def view_context
end
end
DummyController.new
end
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "id"
column "title"
column "published_date"
end
end
it "should generate data with the supplied order" do
expect(builder).to receive(:build_row).and_return([]).once.ordered { |post| expect(post.id).to eq @post2.id }
expect(builder).to receive(:build_row).and_return([]).once.ordered { |post| expect(post.id).to eq @post1.id }
builder.build dummy_controller, []
end
end
context "build csv using specified encoding and encoding_options" do
let(:dummy_controller) do
class DummyController
def in_paginated_batches(&block)
Post.all.each(&block)
end
def view_context
end
end
DummyController.new
end
let(:builder) do
ActiveAdmin::CSVBuilder.new(encoding: encoding, encoding_options: opts) do
column "おはようございます"
column "title"
end
end
context "Shift-JIS with options" do
let(:encoding) { Encoding::Shift_JIS }
let(:opts) { { invalid: :replace, undef: :replace, replace: "?" } }
it "encodes the CSV" do
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line.encoding).to eq(encoding)
end
end
context "ASCII with options" do
let(:encoding) { Encoding::ASCII }
let(:opts) do
{ invalid: :replace, undef: :replace, replace: "__REPLACED__" }
end
it "encodes the CSV without errors" do
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line.encoding).to eq(encoding)
expect(line).to include("__REPLACED__")
end
end
end
context 'csv injection' do
let(:dummy_controller) do
class DummyController
def in_paginated_batches(&block)
Post.all.each(&block)
end
def view_context
MethodOrProcHelper
end
end
DummyController.new
end
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column(:id)
column(:title)
end
end
['=', '+', '-', '@', "\t", "\r"].each do |char|
it "prepends a single quote when column starts with a #{char} character" do
attack = "#{char}1+2"
escaped_attack = "'#{attack}"
escaped_attack = "\"#{escaped_attack}\"" if char == "\r"
post = Post.create!(title: attack)
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line).to eq "#{post.id},#{escaped_attack}\n"
end
it "accounts for the field separator when character #{char} is used to inject a formula" do
attack = "#{char}1+2'\" ;,#{char}1+2"
escaped_attack = "\"'#{attack.gsub('"', '""')}\""
post = Post.create!(title: attack)
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line).to eq "#{post.id},#{escaped_attack}\n"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/menu_spec.rb | spec/unit/menu_spec.rb | # frozen_string_literal: true
require "rails_helper"
require "active_admin/menu"
require "active_admin/menu_item"
include ActiveAdmin
RSpec.describe ActiveAdmin::Menu do
context "with no items" do
it "should have an empty item collection" do
menu = Menu.new
expect(menu.items).to be_empty
end
it "should accept new items" do
menu = Menu.new
menu.add label: "Dashboard"
expect(menu.items.first.label).to eq "Dashboard"
end
end
context "with many items" do
let(:menu) do
Menu.new do |m|
m.add label: "Dashboard"
m.add label: "Blog"
end
end
it "should give access to the menu item as an array" do
expect(menu["Dashboard"].label).to eq "Dashboard"
end
end
describe "adding items with children" do
it "should add an empty item if the parent does not exist" do
menu = Menu.new
menu.add parent: "Admin", label: "Users"
expect(menu["Admin"]["Users"]).to be_an_instance_of(ActiveAdmin::MenuItem)
end
it "should add a child to a parent if it exists" do
menu = Menu.new
menu.add parent: "Admin", label: "Users"
menu.add parent: "Admin", label: "Projects"
expect(menu["Admin"]["Projects"]).to be_an_instance_of(ActiveAdmin::MenuItem)
end
it "should assign children regardless of resource file load order" do
menu = Menu.new
menu.add parent: "Users", label: "Posts"
menu.add label: "Users", url: "/some/url"
expect(menu["Users"].url).to eq "/some/url"
expect(menu["Users"]["Posts"]).to be_a ActiveAdmin::MenuItem
end
end
describe "determining if node is current" do
let(:menu) { Menu.new }
let(:admin_item) { menu.add label: "Admin" }
let(:users_item) { menu.add parent: "Admin", label: "Users" }
let(:posts_item) { menu.add label: "Posts" }
it "should consider item current in relation to itself" do
expect(admin_item.current?(admin_item)).to be true
end
it "should consider item current in relation to a descendent" do
expect(admin_item.current?(users_item)).to be true
end
it "should not consider item current in relation to a non-self/non-descendant" do
expect(admin_item.current?(posts_item)).to be false
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/form_builder_spec.rb | spec/unit/form_builder_spec.rb | # frozen_string_literal: true
require "rails_helper"
require "rspec/mocks/standalone"
RSpec.describe ActiveAdmin::FormBuilder do
# Setup an ActionView::Base object which can be used for
# generating the form for.
let(:helpers) do
view = mock_action_view
def view.posts_path
"/posts"
end
def view.protect_against_forgery?
false
end
def view.url_for(*args)
if args.first == { action: "index" }
posts_path
else
super
end
end
def view.action_name
"edit"
end
view
end
def form_html(options = {}, form_object = Post.new, &block)
options = { url: helpers.posts_path }.merge(options)
render_arbre_component({ form_object: form_object, form_options: options, form_block: block }, helpers) do
active_admin_form_for(assigns[:form_object], assigns[:form_options], &assigns[:form_block])
end.to_s
end
def build_form(options = {}, form_object = Post.new, &block)
form = form_html(options, form_object, &block)
Capybara.string(form)
end
context "in general" do
context "without custom settings" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
end
end
it "should generate a fieldset with a inputs class" do
expect(body).to have_css("fieldset.inputs")
end
end
context "with custom settings" do
let :body do
build_form do |f|
f.inputs class: "custom_class", name: "custom_name", custom_attr: "custom_attr", data: { test: "custom" } do
f.input :title
f.input :body
end
end
end
it "should generate a fieldset with a inputs and custom class" do
expect(body).to have_css("fieldset.custom_class")
end
it "should generate a fieldset with a custom legend" do
expect(body).to have_css("legend", text: "custom_name")
end
it "should generate a fieldset with a custom attributes" do
expect(body).to have_css("fieldset[custom_attr='custom_attr']")
end
it "should use the rails helper for rendering attributes" do
expect(body).to have_css("fieldset[data-test='custom']")
end
end
context "with XSS payload as name" do
let :body do
build_form do |f|
f.inputs name: '<script>alert(document.domain)</script>' do
f.input :title
f.input :body
end
end
end
it "should generate a fieldset with the proper legend" do
expect(body).to have_css("legend", text: "<script>alert(document.domain)</script>")
end
end
end
context "in general with actions" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.actions do
f.action :submit, label: "Submit Me"
f.action :submit, label: "Another Button"
end
end
end
it "should generate a text input" do
expect(body).to have_field("post[title]", type: "text")
end
it "should generate a textarea" do
expect(body).to have_css("textarea[name='post[body]']")
end
it "should only generate the form once" do
expect(body).to have_css("form", count: 1)
end
it "should generate actions" do
expect(body).to have_button("Submit Me")
expect(body).to have_button("Another Button")
end
end
context "when polymorphic relationship" do
it "should raise error" do
expect do
comment = ActiveAdmin::Comment.new
build_form({ url: "admins/comments" }, comment) do |f|
f.inputs :resource
end
end.to raise_error(Formtastic::PolymorphicInputWithoutCollectionError)
end
end
describe "passing in options with actions" do
let :body do
build_form html: { multipart: true } do |f|
f.inputs :title
f.actions
end
end
it "should pass the options on to the form" do
expect(body).to have_css("form[enctype='multipart/form-data']")
end
end
context "file input present" do
let :body do
build_form do |f|
f.input :body, as: :file
end
end
it "adds multipart attribute automatically" do
expect(body).to have_css("form[enctype='multipart/form-data']")
end
end
context "with actions" do
it "should generate the form once" do
body = build_form do |f|
f.inputs do
f.input :title
end
f.actions
end
expect(body).to have_css("[id=post_title]", count: 1)
end
context "create another checkbox" do
subject do
build_form do |f|
f.actions
end
end
%w(new create).each do |action_name|
it "generates create another checkbox on #{action_name} page" do
expect(helpers).to receive(:action_name) { action_name }
allow(helpers).to receive(:active_admin_config) { instance_double(ActiveAdmin::Resource, create_another: true) }
is_expected.to have_css("[type=checkbox]", count: 1)
.and have_css("[name=create_another]", count: 1)
end
end
%w(show edit update).each do |action_name|
it "doesn't generate create another checkbox on #{action_name} page" do
is_expected.to have_no_css("[name=create_another]", count: 1)
end
end
end
it "should generate one button create another checkbox and a cancel link" do
body = build_form do |f|
f.actions
end
expect(body).to have_css("[type=submit]", count: 1)
expect(body).to have_css(".cancel", count: 1)
end
it "should generate multiple actions" do
body = build_form do |f|
f.actions do
f.action :submit, label: "Create & Continue"
f.action :submit, label: "Create & Edit"
end
end
expect(body).to have_css("[type=submit]", count: 2)
expect(body).to have_css(".cancel", count: 0)
end
end
context "with Arbre inside" do
it "should render the Arbre in the expected place" do
body = build_form do |f|
div do
h1 "Heading"
end
f.inputs do
span "Top note"
f.input :title
span "Bottom note"
end
h3 "Footer"
f.actions
end
expect(body).to have_css("div > h1")
expect(body).to have_css("h1", count: 1)
expect(body).to have_css(".inputs > ol > span")
expect(body).to have_css("span", count: 2)
end
it "should allow a simplified syntax" do
body = build_form do |f|
div do
h1 "Heading"
end
inputs do
span "Top note"
input :title
span "Bottom note"
end
h3 "Footer"
actions
end
expect(body).to have_css("div > h1")
expect(body).to have_css("h1", count: 1)
expect(body).to have_css(".inputs > ol > span")
expect(body).to have_css("span", count: 2)
end
end
context "without passing a block to inputs" do
let :body do
build_form do |f|
f.inputs :title, :body
end
end
it "should have a title input" do
expect(body).to have_field("post[title]", type: "text")
end
it "should have a body textarea" do
expect(body).to have_css("textarea[name='post[body]']")
end
end
context "with semantic fields for" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.form_builder.instance_eval do
@object.author = User.new
end
f.semantic_fields_for :author do |author|
author.inputs :first_name, :last_name
end
end
end
it "should generate a nested text input once" do
expect(body).to have_css("[id=post_author_attributes_first_name_input]", count: 1)
end
end
context "with collection inputs" do
before do
User.create first_name: "John", last_name: "Doe"
User.create first_name: "Jane", last_name: "Doe"
end
describe "as select" do
let :body do
build_form do |f|
f.input :author, include_blank: false
end
end
it "should create 2 options" do
expect(body).to have_css("option", count: 2)
end
end
describe "as radio buttons" do
let :body do
build_form do |f|
f.input :author, as: :radio
end
end
it "should create 2 radio buttons" do
expect(body).to have_css("[type=radio]", count: 2)
end
end
end
context "with inputs component inside has_many" do
def user
u = User.new
u.profile = Profile.new(bio: "bio")
u
end
let :body do
author = user()
build_form do |f|
f.form_builder.instance_eval do
@object.author = author
end
f.inputs name: "Author", for: :author do |author|
author.has_many :profile, allow_destroy: true do |profile|
profile.inputs "inputs for profile #{profile.object.bio}" do
profile.input :bio
end
end
end
end
end
it "should see the profile fields for an existing profile" do
expect(body).to have_css("[id='post_author_attributes_profile_attributes_bio']", count: 1)
expect(body).to have_css("textarea[name='post[author_attributes][profile_attributes][bio]']")
end
end
context "with a has_one relation on an author's profile" do
let :body do
author = user()
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.form_builder.instance_eval do
@object.author = author
end
f.inputs name: "Author", for: :author do |author|
author.has_many :profile, allow_destroy: true do |profile|
profile.input :bio
end
end
end
end
it "should see the button to add profile" do
def user
User.new
end
expect(body).to have_css("a[contains(data-html,'post[author_attributes][profile_attributes][bio]')]")
end
it "should see the profile fields for an existing profile" do
def user
u = User.new
u.profile = Profile.new
u
end
expect(body).to have_css("[id='post_author_attributes_profile_attributes_bio']", count: 1)
expect(body).to have_css("textarea[name='post[author_attributes][profile_attributes][bio]']")
end
end
shared_examples :inputs_with_for_expectation do
it "should generate a nested text input once" do
expect(body).to have_css("[id=post_author_attributes_first_name_input]", count: 1)
expect(body).to have_css("[id=post_author_attributes_last_name_input]", count: 1)
end
it "should add author first and last name fields" do
expect(body).to have_field("post[author_attributes][first_name]")
expect(body).to have_field("post[author_attributes][last_name]")
end
end
context "with inputs 'for'" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.form_builder.instance_eval do
@object.author = User.new
end
f.inputs name: "Author", for: :author do |author|
author.inputs :first_name, :last_name
end
end
end
include_examples :inputs_with_for_expectation
end
context "with two input fields 'for' at the end of block" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.form_builder.instance_eval do
@object.author = User.new
end
f.inputs name: "Author", for: :author do |author|
author.input :first_name
author.input :last_name
end
end
end
include_examples :inputs_with_for_expectation
end
context "with two input fields 'for' at the beginning of block" do
let :body do
build_form do |f|
f.form_builder.instance_eval do
@object.author = User.new
end
f.inputs name: "Author", for: :author do |author|
author.input :first_name
author.input :last_name
end
f.inputs do
f.input :title
f.input :body
end
end
end
include_examples :inputs_with_for_expectation
end
context "with wrapper html" do
it "should set a class" do
body = build_form do |f|
f.input :title, wrapper_html: { class: "important" }
end
expect(body).to have_css("li[class='important string input optional stringish']")
end
end
context "with inputs twice" do
let :body do
build_form do |f|
f.inputs do
f.input :title
f.input :body
end
f.inputs do
f.input :author
f.input :created_at
end
end
end
it "should render four inputs" do
expect(body).to have_field("post[title]", count: 1)
expect(body).to have_css("textarea[name='post[body]']", count: 1)
expect(body).to have_select("post[author_id]", count: 1)
expect(body).to have_select("post[created_at(1i)]", count: 1)
expect(body).to have_select("post[created_at(2i)]", count: 1)
expect(body).to have_select("post[created_at(3i)]", count: 1)
expect(body).to have_select("post[created_at(4i)]", count: 1)
end
end
context "with has many inputs" do
describe "with simple block" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts do |p|
p.input :title
p.input :body
end
f.inputs
end
end
let(:valid_html_id) { /^[A-Za-z]+[\w\-\:\.]*$/ }
it "should translate the association name in header" do
with_translation %i[activerecord models post one], "Blog Post" do
with_translation %i[activerecord models post other], "Blog Posts" do
expect(body).to have_css("h3", text: "Blog Posts")
end
end
end
it "should use model name when there is no translation for given model in header" do
expect(body).to have_css("h3", text: "Post")
end
it "should translate the association name in has many new button" do
with_translation %i[activerecord models post one], "Blog Post" do
with_translation %i[activerecord models post other], "Blog Posts" do
expect(body).to have_css("a", text: "Add New Blog Post")
end
end
end
it "should translate the attribute name" do
with_translation %i[activerecord attributes post title], "A very nice title" do
expect(body).to have_css("label", text: "A very nice title")
end
end
it "should use model name when there is no translation for given model in has many new button" do
expect(body).to have_css("a", text: "Add New Post")
end
it "should render the nested form" do
expect(body).to have_field("category[posts_attributes][0][title]")
expect(body).to have_css("textarea[name='category[posts_attributes][0][body]']")
end
it "should add a link to remove new nested records" do
expect(body).to have_css(".has-many-container > fieldset > ol > li > a.has-many-remove[href='#']", text: "Remove")
end
it "should add a link to add new nested records" do
expect(body).to have_css(".has-many-container > a.has-many-add[href='#']", text: "Add New Post")
end
it "should set an HTML-id valid placeholder" do
link = body.find(".has-many-container > a.has-many-add")
expect(link[:'data-placeholder']).to match valid_html_id
end
describe "with namespaced model" do
it "should set an HTML-id valid placeholder" do
allow(Post).to receive(:name).and_return "ActiveAdmin::Post"
link = body.find(".has-many-container > a.has-many-add")
expect(link[:'data-placeholder']).to match valid_html_id
end
end
end
describe "with complex block" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts do |p, i|
p.input :title, label: "Title #{i}"
end
end
end
it "should accept a block with a second argument" do
expect(body).to have_css("label", text: "Title 1")
end
it "should add a custom header" do
expect(body).to have_css("h3", text: "Post")
end
end
describe "without heading and new record link" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, heading: false, new_record: false do |p|
p.input :title
end
end
end
it "should not add a header" do
expect(body).to have_no_css("h3", text: "Post")
end
it "should not add link to new nested records" do
expect(body).to have_no_css("a", text: "Add New Post")
end
it "should render the nested form" do
expect(body).to have_field("category[posts_attributes][0][title]")
end
end
describe "with custom heading" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, heading: "Test heading" do |p|
p.input :title
end
end
end
it "should add a custom header" do
expect(body).to have_css("h3", text: "Test heading")
end
end
describe "with custom new record link" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, new_record: "My Custom New Post" do |p|
p.input :title
end
end
end
it "should add a custom new record link" do
expect(body).to have_css("a", text: "My Custom New Post")
end
end
describe "with custom class" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, class: 'myclass' do |p|
p.input :title
end
end
end
it "should generate a fieldset with the given class" do
expect(body).to have_css(".has-many-container > fieldset.myclass")
end
it "should add the custom class on the fieldset generated by the new record link" do
link = body.find(".has-many-container > a.has-many-add")
new_record_html = Capybara.string(link[:'data-html'])
expect(new_record_html).to have_css("fieldset.myclass")
end
end
describe "with custom attributes" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, attr: "value", data: { 'custom-attribute': "custom-value" } do |p|
p.input :title
end
end
end
it "should generate a fieldset with the given custom attributes" do
expect(body).to have_css(".has-many-container > fieldset[attr='value'][data-custom-attribute='custom-value']")
end
it "should add custom attributes on the fieldset generated by the new record link" do
link = body.find(".has-many-container > a.has-many-add")
new_record_html = Capybara.string(link[:'data-html'])
expect(new_record_html).to have_css("fieldset[attr='value'][data-custom-attribute='custom-value']")
end
end
describe "with allow destroy" do
shared_examples_for "has many with allow_destroy = true" do |child_num|
it "should render the nested form" do
expect(body).to have_field("category[posts_attributes][#{child_num}][title]")
end
it "should include a boolean field for _destroy" do
expect(body).to have_field("category[posts_attributes][#{child_num}][_destroy]")
end
it "should have a check box with 'Remove' as its label" do
expect(body).to have_css("label[for=category_posts_attributes_#{child_num}__destroy]", text: "Delete")
end
it "should wrap the destroy field in an li with class 'has-many-delete'" do
expect(body).to have_css(".has-many-container > fieldset > ol > li.has-many-delete > input", count: 1, visible: :hidden)
end
end
shared_examples_for "has many with allow_destroy = false" do |child_num|
it "should render the nested form" do
expect(body).to have_field("category[posts_attributes][#{child_num}][title]")
end
it "should not have a boolean field for _destroy" do
expect(body).to have_no_field("category[posts_attributes][#{child_num}][_destroy]", visible: :all)
end
it "should not have a check box with 'Remove' as its label" do
expect(body).to have_no_css("label[for=category_posts_attributes_#{child_num}__destroy]", text: "Remove")
end
end
shared_examples_for "has many with allow_destroy as String, Symbol or Proc" do |allow_destroy_option|
let :body do
s = self
build_form({ url: "/categories" }, Category.new) do |f|
s.instance_exec do
allow(f.object.posts.build).to receive(:foo?).and_return(true)
allow(f.object.posts.build).to receive(:foo?).and_return(false)
f.object.posts.each do |post|
allow(post).to receive(:new_record?).and_return(false)
end
end
f.has_many :posts, allow_destroy: allow_destroy_option do |p|
p.input :title
end
end
end
context "for the child that responds with true" do
it_behaves_like "has many with allow_destroy = true", 0
end
context "for the child that responds with false" do
it_behaves_like "has many with allow_destroy = false", 1
end
end
context "with an existing post" do
context "with allow_destroy = true" do
let :body do
s = self
build_form({ url: "/categories" }, Category.new) do |f|
s.instance_exec do
allow(f.object.posts.build).to receive(:new_record?).and_return(false)
end
f.has_many :posts, allow_destroy: true do |p|
p.input :title
end
end
end
it_behaves_like "has many with allow_destroy = true", 0
end
context "with allow_destroy = false" do
let :body do
s = self
build_form({ url: "/categories" }, Category.new) do |f|
s.instance_exec do
allow(f.object.posts.build).to receive(:new_record?).and_return(false)
end
f.has_many :posts, allow_destroy: false do |p|
p.input :title
end
end
end
it_behaves_like "has many with allow_destroy = false", 0
end
context "with allow_destroy = nil" do
let :body do
s = self
build_form({ url: "/categories" }, Category.new) do |f|
s.instance_exec do
allow(f.object.posts.build).to receive(:new_record?).and_return(false)
end
f.has_many :posts, allow_destroy: nil do |p|
p.input :title
end
end
end
it_behaves_like "has many with allow_destroy = false", 0
end
context "with allow_destroy as Symbol" do
it_behaves_like("has many with allow_destroy as String, Symbol or Proc", :foo?)
end
context "with allow_destroy as String" do
it_behaves_like("has many with allow_destroy as String, Symbol or Proc", "foo?")
end
context "with allow_destroy as proc" do
it_behaves_like(
"has many with allow_destroy as String, Symbol or Proc",
Proc.new { |child| child.foo? })
end
context "with allow_destroy as lambda" do
it_behaves_like(
"has many with allow_destroy as String, Symbol or Proc",
lambda { |child| child.foo? })
end
context "with allow_destroy as any other expression that evaluates to true" do
let :body do
s = self
build_form({ url: "/categories" }, Category.new) do |f|
s.instance_exec do
allow(f.object.posts.build).to receive(:new_record?).and_return(false)
end
f.has_many :posts, allow_destroy: Object.new do |p|
p.input :title
end
end
end
it_behaves_like "has many with allow_destroy = true", 0
end
end
context "with a new post" do
context "with allow_destroy = true" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, allow_destroy: true do |p|
p.input :title
end
end
end
it_behaves_like "has many with allow_destroy = false", 0
end
end
end
describe "sortable" do
# TODO: it doesn't make any sense to use your foreign key as something that's sortable (and therefore editable)
context "with a new post" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, sortable: :position do |p|
p.input :title
end
end
end
it "shows the nested fields for unsaved records" do
expect(body).to have_css("fieldset.inputs.has-many-fields")
end
end
context "with post returning nil for the sortable attribute" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build position: 3
f.object.posts.build
f.has_many :posts, sortable: :position do |p|
p.input :title
end
end
end
it "shows the nested fields for unsaved records" do
expect(body).to have_css("fieldset.inputs.has-many-fields")
end
end
context "with existing and new posts" do
let! :category do
Category.create name: "Name"
end
let! :post do
category.posts.create
end
let :body do
build_form({ url: "/categories" }, category) do |f|
f.object.posts.build
f.has_many :posts, sortable: :position do |p|
p.input :title
end
end
end
it "shows the nested fields for saved and unsaved records" do
expect(body).to have_css("fieldset.inputs.has-many-fields")
end
end
context "without sortable_start set" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, sortable: :position do |p|
p.input :title
end
end
end
it "defaults to 0" do
expect(body).to have_css("div.has-many-container[data-sortable-start='0']")
end
end
context "with sortable_start set" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts, sortable: :position, sortable_start: 15 do |p|
p.input :title
end
end
end
it "sets the data attribute" do
expect(body).to have_css("div.has-many-container[data-sortable-start='15']")
end
end
end
describe "with nesting" do
context "in an inputs block" do
let :body do
build_form({ url: "/categories" }, Category.new) do |f|
f.inputs "Field Wrapper" do
f.object.posts.build
f.has_many :posts do |p|
p.input :title
end
end
end
end
it "should wrap the has_many fieldset in an li" do
expect(body).to have_css("ol > li.has-many-container")
end
it "should have a direct fieldset child" do
expect(body).to have_css("li.has-many-container > fieldset")
end
it "should not contain invalid li children" do
expect(body).to have_no_css("div.has-many-container > li")
end
end
context "in another has_many block" do
let :body_html do
form_html({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts do |p|
p.object.taggings.build
p.input :title
p.has_many :taggings do |t|
t.input :tag
t.input :position
end
end
end
end
let(:body) { Capybara.string body_html }
it "displays the input between the outer and inner has_many" do
expect(body).to have_css(".has-many-container ol > li:first-child input#category_posts_attributes_0_title")
expect(body).to have_css(".has-many-container ol > li:nth-child(2).has-many-container > fieldset")
end
it "should not contain invalid li children" do
expect(body).to have_no_css(".has-many-container div.has-many-container > li")
end
end
end
it "should render the block if it returns nil" do
body = build_form({ url: "/categories" }, Category.new) do |f|
f.object.posts.build
f.has_many :posts do |p|
p.input :title
nil
end
end
expect(body).to have_field("category[posts_attributes][0][title]")
end
end
{ # Testing that the same input can be used multiple times
"f.input :title, as: :string" => "post_title",
"f.input :title, as: :text" => "post_title",
"f.input :created_at, as: :time_select" => "post_created_at_2i",
"f.input :created_at, as: :datetime_select" => "post_created_at_2i",
"f.input :created_at, as: :date_select" => "post_created_at_2i",
# Testing that return values don't screw up the form
"f.input :title; nil" => "post_title",
"f.input :title; []" => "post_title",
"[:title].each{ |r| f.input r }" => "post_title",
"[:title].map { |r| f.input r }" => "post_title",
}.each do |source, selector|
it "should properly buffer `#{source}`" do
body = build_form do |f|
f.inputs do
eval source
eval source
end
end
expect(body).to have_css("[id=#{selector}]", count: 2, visible: :all)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/belongs_to_spec.rb | spec/unit/belongs_to_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource::BelongsTo do
around do |example|
with_resources_during(example) do
ActiveAdmin.register User
ActiveAdmin.register(Post) { belongs_to :user }
end
end
let(:user_config) { ActiveAdmin.register User }
let(:post_config) { ActiveAdmin.register(Post) { belongs_to :user } }
let(:belongs_to) { post_config.belongs_to_config }
it "should have an owner" do
expect(belongs_to.owner).to eq post_config
end
describe "finding the target" do
context "when the resource has been registered" do
it "should return the target resource" do
expect(belongs_to.target).to eq user_config
end
end
context "when the resource has not been registered" do
let(:belongs_to) { ActiveAdmin::Resource::BelongsTo.new post_config, :missing }
it "should raise a ActiveAdmin::BelongsTo::TargetNotFound" do
expect do
belongs_to.target
end.to raise_error(ActiveAdmin::Resource::BelongsTo::TargetNotFound)
end
end
context "when the resource is on a namespace" do
let(:blog_post_config) { ActiveAdmin.register Blog::Post }
let(:belongs_to) { ActiveAdmin::Resource::BelongsTo.new blog_post_config, :blog_author, class_name: "Blog::Author" }
before do
class Blog::Author
include ActiveModel::Naming
end
@blog_author_config = ActiveAdmin.register Blog::Author
end
it "should return the target resource" do
expect(belongs_to.target).to eq @blog_author_config
end
end
end
it "should be optional" do
belongs_to = ActiveAdmin::Resource::BelongsTo.new post_config, :user, optional: true
expect(belongs_to).to be_optional
end
describe "controller" do
let(:controller) { post_config.controller.new }
let(:http_params) { { user_id: user.id } }
let(:user) { User.create! }
before do
request = double "Request", format: "application/json"
allow(controller).to receive(:params) { ActionController::Parameters.new(http_params) }
allow(controller).to receive(:request) { request }
end
it "should be able to access the collection" do
expect(controller.send :collection).to be_a ActiveRecord::Relation
end
it "should be able to build a new resource" do
expect(controller.send :build_resource).to be_a Post
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/dynamic_settings_spec.rb | spec/unit/dynamic_settings_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::DynamicSettingsNode do
subject { ActiveAdmin::DynamicSettingsNode.build }
context "StringSymbolOrProcSetting" do
before { subject.register :foo, "bar", :string_symbol_or_proc }
it "should pass through a string" do
subject.foo = "string"
expect(subject.foo(self)).to eq "string"
end
it "should instance_exec if context given" do
ctx = Hash[i: 42]
subject.foo = proc { self[:i] += 1 }
expect(subject.foo(ctx)).to eq 43
expect(subject.foo(ctx)).to eq 44
end
it "should send message if symbol given" do
ctx = double
expect(ctx).to receive(:quux).and_return "qqq"
subject.foo = :quux
expect(subject.foo(ctx)).to eq "qqq"
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/namespace_spec.rb | spec/unit/namespace_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Namespace do
let(:application) { ActiveAdmin::Application.new }
context "when new" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
it "should have an application instance" do
expect(namespace.application).to eq application
end
it "should have a name" do
expect(namespace.name).to eq :admin
end
it "should have no resources" do
expect(namespace.resources).to be_empty
end
it "should not have any menu item" do
expect(namespace.fetch_menu(:default).children).to be_empty
end
end # context "when new"
describe "#unload!" do
context "when controller is only defined without a namespace" do
before do
# To ensure Admin::PostsController is defined
ActiveAdmin.register Post
# To ensure ::PostsController is defined
ActiveAdmin.register Post, namespace: false
# To prevent unload! from unregistering ::PostsController
ActiveAdmin.application.namespaces.instance_variable_get(:@namespaces).delete(:root)
# To force Admin::PostsController to not be there
Admin.send(:remove_const, "PostsController")
end
after do
load_resources {}
end
it "should not crash" do
expect { ActiveAdmin.unload! }.not_to raise_error
end
end
end
describe "settings" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
it "should inherit the site title from the application" do
ActiveAdmin.deprecator.silence do
ActiveAdmin::Namespace.setting :site_title, "Not the Same"
end
expect(namespace.site_title).to eq application.site_title
end
it "should be able to override the site title" do
expect(namespace.site_title).to eq application.site_title
namespace.site_title = "My Site Title"
expect(namespace.site_title).to_not eq application.site_title
end
end
describe "#fetch_menu" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
it "returns the menu" do
expect(namespace.fetch_menu(:default)).to be_an_instance_of(ActiveAdmin::Menu)
end
it "should raise an exception if the menu doesn't exist" do
expect do
namespace.fetch_menu(:not_a_menu_that_exists)
end.to raise_error(KeyError)
end
end
describe "#build_menu" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
it "should set the block as a menu build callback" do
namespace.build_menu do |menu|
menu.add label: "menu item"
end
expect(namespace.fetch_menu(:default)["menu item"]).to_not eq nil
end
it "should set a block on a custom menu" do
namespace.build_menu :test do |menu|
menu.add label: "menu item"
end
expect(namespace.fetch_menu(:test)["menu item"]).to_not eq nil
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/application_spec.rb | spec/unit/application_spec.rb | # frozen_string_literal: true
require "rails_helper"
require "fileutils"
RSpec.describe ActiveAdmin::Application do
let(:application) { ActiveAdmin::Application.new }
it "should have a default load path of ['app/admin']" do
expect(application.load_paths).to eq [File.expand_path("app/admin", application.app_path)]
end
describe "#prepare" do
before { application.prepare! }
it "should remove app/admin from the autoload paths" do
expect(ActiveSupport::Dependencies.autoload_paths).to_not include(Rails.root.join("app/admin"))
end
end
it "should store the site's title" do
expect(application.site_title).to eq ""
end
it "should set the site title" do
application.site_title = "New Title"
expect(application.site_title).to eq "New Title"
end
it "should set the site title using a block" do
application.site_title = proc { "Block Title" }
expect(application.site_title).to eq "Block Title"
end
it "should return default localize format" do
expect(application.localize_format).to eq :long
end
it "should set localize format" do
application.localize_format = :default
expect(application.localize_format).to eq :default
end
it "should allow comments by default" do
expect(application.comments).to eq true
end
it "should have default order clause class" do
expect(application.order_clause).to eq ActiveAdmin::OrderClause
end
it "should have default show_count for scopes" do
expect(application.scopes_show_count).to eq true
end
it "fails if setting undefined" do
expect do
application.undefined_setting
end.to raise_error(NoMethodError)
end
describe "authentication settings" do
it "should have no default current_user_method" do
expect(application.current_user_method).to eq false
end
it "should have no default authentication method" do
expect(application.authentication_method).to eq false
end
it "should have a logout link path (Devise's default)" do
expect(application.logout_link_path).to eq :destroy_admin_user_session_path
end
end
describe "files in load path" do
it "it should load sorted files" do
expect(application.files.map { |f| File.basename(f) }).to eq(%w(admin_users.rb companies.rb dashboard.rb stores.rb))
end
it "should load files in the first level directory" do
expect(application.files).to include(File.expand_path("app/admin/dashboard.rb", application.app_path))
end
it "should load files from subdirectories", :changes_filesystem do
test_dir = File.expand_path("app/admin/public", application.app_path)
test_file = File.expand_path("app/admin/public/posts.rb", application.app_path)
begin
FileUtils.mkdir_p(test_dir)
FileUtils.touch(test_file)
expect(application.files).to include(test_file)
ensure
FileUtils.remove_entry_secure(test_dir, force: true)
end
end
it "should honor load paths order", :changes_filesystem do
test_dir = File.expand_path("app/other-admin", application.app_path)
test_file = File.expand_path("app/other-admin/posts.rb", application.app_path)
application.load_paths.unshift(test_dir)
begin
FileUtils.mkdir_p(test_dir)
FileUtils.touch(test_file)
expect(application.files.map { |f| File.basename(f) }).to eq(%w(posts.rb admin_users.rb companies.rb dashboard.rb stores.rb))
ensure
FileUtils.remove_entry_secure(test_dir, force: true)
end
end
end
describe "#namespace" do
it "should yield a new namespace" do
application.namespace :new_namespace do |ns|
expect(ns.name).to eq :new_namespace
end
end
it "should return an instantiated namespace" do
admin = application.namespace :admin
expect(admin).to eq application.namespaces[:admin]
end
it "should yield an existing namespace" do
expect do
application.namespace :admin do |ns|
expect(ns).to eq application.namespaces[:admin]
raise "found"
end
end.to raise_error("found")
end
it "should admit both strings and symbols" do
expect do
application.namespace "admin" do |ns|
expect(ns).to eq application.namespaces[:admin]
raise "found"
end
end.to raise_error("found")
end
it "should not pollute the global app" do
expect(application.namespaces).to be_empty
application.namespace(:brand_new_ns)
expect(application.namespaces.names).to eq [:brand_new_ns]
expect(ActiveAdmin.application.namespaces.names).to eq [:admin]
end
end
describe "#register_page" do
it "finds or create the namespace and register the page to it" do
namespace = double
expect(application).to receive(:namespace).with("public").and_return namespace
expect(namespace).to receive(:register_page).with("My Page", { namespace: "public" })
application.register_page("My Page", namespace: "public")
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/pundit_adapter_spec.rb | spec/unit/pundit_adapter_spec.rb | # frozen_string_literal: true
require "rails_helper"
class DefaultPolicy < ApplicationPolicy
def respond_to_missing?(method, include_private = false)
method.to_s[0...3] == "foo" || super
end
def method_missing(method, *args, &block)
method.to_s[4...7] == "yes" if method.to_s[0...3] == "foo"
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope
end
end
end
RSpec.describe ActiveAdmin::PunditAdapter do
describe "full integration" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, "Admin") }
let(:resource) { namespace.register(Post) }
let(:user) { User.new }
let(:auth) { namespace.authorization_adapter.new(resource, user) }
let(:default_policy_klass) { DefaultPolicy }
let(:default_policy_klass_name) { "DefaultPolicy" }
before do
namespace.authorization_adapter = ActiveAdmin::PunditAdapter
end
it "should initialize the ability stored in the namespace configuration" do
expect(auth.authorized?(:read, Post)).to eq true
expect(auth.authorized?(:update, Post)).to eq false
end
it "should allow differentiating between new and create" do
expect(auth.authorized?(:new, Post)).to eq true
expect(auth.authorized?(ActiveAdmin::Auth::NEW, Post)).to eq true
announcement_category = Category.new(name: "Announcements")
announcement_post = Post.new(title: "Big announcement", category: announcement_category)
expect(auth.authorized?(:create, announcement_post)).to eq false
expect(auth.authorized?(ActiveAdmin::Auth::CREATE, announcement_post)).to eq false
end
it "should scope the collection" do
class RSpec::Mocks::DoublePolicy < ApplicationPolicy
class Scope < Struct.new(:user, :scope)
def resolve
scope
end
end
end
collection = double
auth.scope_collection(collection, :read)
expect(collection).to eq collection
end
it "works well with method_missing" do
allow(auth).to receive(:retrieve_policy).and_return(DefaultPolicy.new(double, double))
expect(auth.authorized?(:foo_no)).to eq false
expect(auth.authorized?(:foo_yes)).to eq true
expect(auth.authorized?(:bar_yes)).to eq false
end
context "when Pundit namespace provided" do
before do
allow(ActiveAdmin.application).to receive(:pundit_policy_namespace).and_return :foobar
end
it "looks for a namespaced policy" do
expect(Pundit).to receive(:policy).with(anything, [:foobar, Post]).and_return(DefaultPolicy.new(double, double))
auth.authorized?(:read, Post)
end
it "looks for a namespaced policy scope" do
collection = double
expect(Pundit).to receive(:policy_scope!).with(anything, [:foobar, collection]).and_return(DefaultPolicy::Scope.new(double, double))
auth.scope_collection(collection, :read)
end
it "uses the resource when no subject given" do
expect(Pundit).to receive(:policy).with(anything, [:foobar, resource]).and_return(DefaultPolicy::Scope.new(double, double))
auth.authorized?(:index)
end
end
it "uses the resource when no subject given" do
expect(Pundit).to receive(:policy).with(anything, resource).and_return(DefaultPolicy::Scope.new(double, double))
auth.authorized?(:index)
end
context "when model name contains policy namespace name" do
include_context "capture stderr"
before do
allow(ActiveAdmin.application).to receive(:pundit_policy_namespace).and_return :pub
namespace.register(Publisher)
ActiveAdmin.deprecator.behavior = :stderr
end
after do
ActiveAdmin.deprecator.behavior = :raise
end
it "looks for a namespaced policy" do
expect(Pundit).to receive(:policy).with(anything, [:pub, Publisher]).and_return(DefaultPolicy.new(double, double))
auth.authorized?(:read, Publisher)
end
it "fallbacks to the policy without namespace" do
expect(Pundit).to receive(:policy).with(anything, [:pub, Publisher]).and_return(nil)
expect(Pundit).to receive(:policy).with(anything, Publisher).and_return(DefaultPolicy.new(double, double))
auth.authorized?(:read, Publisher)
expect($stderr.string).to include("ActiveAdmin was unable to find policy Pub::DefaultPolicy. DefaultPolicy will be used instead.")
end
end
context "when Pundit is unable to find policy scope" do
let(:collection) { double("collection", to_sym: :collection) }
subject(:scope) { auth.scope_collection(collection, :read) }
before do
allow(ActiveAdmin.application).to receive(:pundit_default_policy).and_return default_policy_klass_name
allow(Pundit).to receive(:policy_scope!) { raise Pundit::NotDefinedError.new }
end
it("should return default policy's scope if defined") { is_expected.to eq(collection) }
context "and default policy doesn't exist" do
let(:default_policy_klass_name) { nil }
it "raises the error" do
expect { subject }.to raise_error Pundit::NotDefinedError
end
end
end
context "when Pundit is unable to find policy" do
let(:record) { double }
subject(:policy) { auth.retrieve_policy(record) }
before do
allow(ActiveAdmin.application).to receive(:pundit_default_policy).and_return default_policy_klass_name
allow(Pundit).to receive(:policy) { nil }
end
it("should return default policy instance") { is_expected.to be_instance_of(default_policy_klass) }
context "and default policy doesn't exist" do
let(:default_policy_klass_name) { nil }
it "raises the error" do
expect { subject }.to raise_error Pundit::NotDefinedError
end
end
end
context "when retrieve_policy is given a page and namespace is :active_admin" do
let(:page) { namespace.register_page "Dashboard" }
subject(:policy) { auth.retrieve_policy(page) }
before do
allow(ActiveAdmin.application).to receive(:pundit_policy_namespace).and_return :active_admin
end
it("should return page policy instance") { is_expected.to be_instance_of(ActiveAdmin::PagePolicy) }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/config_shared_examples.rb | spec/unit/config_shared_examples.rb | # frozen_string_literal: true
RSpec.shared_examples_for "ActiveAdmin::Resource" do
describe "namespace" do
it "should return the namespace" do
expect(config.namespace).to eq(namespace)
end
end
describe "page_presenters" do
it "should return an empty hash by default" do
expect(config.page_presenters).to eq({})
end
end
it { respond_to :controller_name }
it { respond_to :controller }
it { respond_to :route_prefix }
it { respond_to :route_collection_path }
it { respond_to :comments? }
it { respond_to :belongs_to? }
it { respond_to :action_items? }
it { respond_to :sidebar_sections? }
describe "Naming" do
it "implements #resource_label" do
expect { config.resource_label }.to_not raise_error
end
it "implements #plural_resource_label" do
expect { config.plural_resource_label }.to_not raise_error
end
end
describe "Menu" do
describe "#menu_item_options" do
it "initializes a new menu item with defaults" do
expect(config.menu_item_options[:label].call).to eq(config.plural_resource_label)
end
it "initialize a new menu item with custom options" do
config.menu_item_options = { label: "Hello" }
expect(config.menu_item_options[:label]).to eq("Hello")
end
end
describe "#include_in_menu?" do
it "should be included in menu by default" do
expect(config.include_in_menu?).to eq(true)
end
it "should not be included in menu when menu set to false" do
config.menu_item_options = false
expect(config.include_in_menu?).to eq(false)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/cancan_adapter_spec.rb | spec/unit/cancan_adapter_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::CanCanAdapter do
describe "full integration" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, "Admin") }
let(:resource) { namespace.register(Post) }
let :ability_class do
Class.new do
include CanCan::Ability
def initialize(user)
can :read, Post
can :create, Post
cannot :update, Post
end
end
end
let(:auth) { namespace.authorization_adapter.new(resource, double) }
before do
namespace.authorization_adapter = ActiveAdmin::CanCanAdapter
namespace.cancan_ability_class = ability_class
end
it "should initialize the ability stored in the namespace configuration" do
expect(auth.authorized?(:read, Post)).to eq true
expect(auth.authorized?(:update, Post)).to eq false
end
it "should treat :new ability the same as :create" do
expect(auth.authorized?(:new, Post)).to eq true
expect(auth.authorized?(:create, Post)).to eq true
end
it "should scope the collection with accessible_by" do
collection = double
expect(collection).to receive(:accessible_by).with(auth.cancan_ability, :edit)
auth.scope_collection(collection, :edit)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_spec.rb | spec/unit/resource_spec.rb | # frozen_string_literal: true
require "rails_helper"
require File.expand_path("config_shared_examples", __dir__)
module ActiveAdmin
RSpec.describe Resource do
it_should_behave_like "ActiveAdmin::Resource"
around do |example|
with_resources_during(example) { namespace.register Category }
end
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { Namespace.new(application, :admin) }
def config(options = {})
@config ||= Resource.new(namespace, Category, options)
end
it { respond_to :resource_class }
describe "#resource_table_name" do
it "should return the resource's table name" do
expect(config.resource_table_name).to eq '"categories"'
end
context "when the :as option is given" do
it "should return the resource's table name" do
expect(config(as: "My Category").resource_table_name).to eq '"categories"'
end
end
end
describe "#resource_column_names" do
it "should return the resource's column names" do
expect(config.resource_column_names).to eq Category.column_names
end
end
describe "#decorator_class" do
it "returns nil by default" do
expect(config.decorator_class).to eq nil
end
context "when a decorator is defined" do
around do |example|
with_resources_during(example) { resource }
end
let(:resource) { namespace.register(Post) { decorate_with PostDecorator } }
specify "#decorator_class_name should return PostDecorator" do
expect(resource.decorator_class_name).to eq "::PostDecorator"
end
it "returns the decorator class" do
expect(resource.decorator_class).to eq PostDecorator
end
end
end
describe "controller name" do
it "should return a namespaced controller name" do
expect(config.controller_name).to eq "Admin::CategoriesController"
end
context "when non namespaced controller" do
let(:namespace) { ActiveAdmin::Namespace.new(application, :root) }
it "should return a non namespaced controller name" do
expect(config.controller_name).to eq "CategoriesController"
end
end
end
describe "#include_in_menu?" do
subject { resource }
around do |example|
with_resources_during(example) { resource }
end
context "when regular resource" do
let(:resource) { namespace.register(Post) }
it { is_expected.to be_include_in_menu }
end
context "when menu set to false" do
let(:resource) { namespace.register(Post) { menu false } }
it { is_expected.not_to be_include_in_menu }
end
end
describe "#belongs_to" do
it "should build a belongs to configuration" do
expect(config.belongs_to_config).to eq nil
config.belongs_to :posts
expect(config.belongs_to_config).to_not eq nil
end
it "should not set the target menu to the belongs to target" do
expect(config.navigation_menu_name).to eq ActiveAdmin::DEFAULT_MENU
config.belongs_to :posts
expect(config.navigation_menu_name).to eq ActiveAdmin::DEFAULT_MENU
end
end
describe "scoping" do
context "when using a block" do
before do
@resource = application.register Category do
scope_to do
"scoped"
end
end
end
it "should call the proc for the begin of association chain" do
begin_of_association_chain = @resource.controller.new.send(:begin_of_association_chain)
expect(begin_of_association_chain).to eq "scoped"
end
end
context "when using a symbol" do
before do
@resource = application.register Category do
scope_to :current_user
end
end
it "should call the method for the begin of association chain" do
controller = @resource.controller.new
expect(controller).to receive(:current_user).and_return(true)
begin_of_association_chain = controller.send(:begin_of_association_chain)
expect(begin_of_association_chain).to eq true
end
end
describe "getting the method for the association chain" do
context "when a simple registration" do
before do
@resource = application.register Category do
scope_to :current_user
end
end
it "should return the pluralized collection name" do
expect(@resource.controller.new.send(:method_for_association_chain)).to eq :categories
end
end
context "when passing in the method as an option" do
before do
@resource = application.register Category do
scope_to :current_user, association_method: :blog_categories
end
end
it "should return the method from the option" do
expect(@resource.controller.new.send(:method_for_association_chain)).to eq :blog_categories
end
end
end
end
describe "sort order" do
class MockResource
end
context "when resource class responds to primary_key" do
it "should sort by primary key desc by default" do
expect(MockResource).to receive(:primary_key).and_return("pk")
config = Resource.new(namespace, MockResource)
expect(config.sort_order).to eq "pk_desc"
end
end
context "when resource class does not respond to primary_key" do
it "should default to id" do
config = Resource.new(namespace, MockResource)
expect(config.sort_order).to eq "id_desc"
end
end
it "should be set-able" do
config.sort_order = "task_id_desc"
expect(config.sort_order).to eq "task_id_desc"
end
end
describe "adding a scope" do
it "should add a scope" do
config.scope :published
expect(config.scopes.first).to be_a(ActiveAdmin::Scope)
expect(config.scopes.first.name).to eq "Published"
expect(config.scopes.first.show_count).to eq true
end
context "when show_count disabled" do
it "should add a scope show_count = false" do
namespace.scopes_show_count = false
config.scope :published
expect(config.scopes.first.show_count).to eq false
end
end
it "should retrieve a scope by its id" do
config.scope :published
expect(config.get_scope_by_id(:published).name).to eq "Published"
end
it "should retrieve the default scope by proc" do
config.scope :published, default: proc { true }
config.scope :all
expect(config.default_scope.name).to eq "Published"
end
end
describe "#csv_builder" do
context "when no csv builder set" do
it "should return a default column builder with id and content columns" do
expect(config.csv_builder.exec_columns.size).to eq @config.content_columns.size + 1
end
end
context "when csv builder set" do
it "should return the csv_builder we set" do
csv_builder = CSVBuilder.new
config.csv_builder = csv_builder
expect(config.csv_builder).to eq csv_builder
end
end
end
describe "#breadcrumb" do
subject { config.breadcrumb }
context "when no breadcrumb is set" do
it { is_expected.to eq(namespace.breadcrumb) }
end
context "when breadcrumb is set" do
context "when set to true" do
before { config.breadcrumb = true }
it { is_expected.to eq true }
end
context "when set to false" do
before { config.breadcrumb = false }
it { is_expected.to eq false }
end
end
end
describe "#find_resource" do
let(:post) { double }
around do |example|
with_resources_during(example) { resource }
end
context "without a decorator" do
let(:resource) { namespace.register(Post) }
it "can find the resource" do
allow(Post).to receive(:find_by).with({ "id" => "12345" }) { post }
expect(resource.find_resource("12345")).to eq post
end
end
context "with a decorator" do
let(:resource) { namespace.register(Post) { decorate_with PostDecorator } }
it "decorates the resource" do
allow(Post).to receive(:find_by).with({ "id" => "12345" }) { post }
expect(resource.find_resource("12345")).to eq PostDecorator.new(post)
end
it "does not decorate a not found resource" do
allow(Post).to receive(:find_by).with({ "id" => "54321" }) { nil }
expect(resource.find_resource("54321")).to equal nil
end
end
context "when using a nonstandard primary key" do
let(:resource) { namespace.register(Post) }
before do
allow(Post).to receive(:primary_key).and_return "something_else"
allow(Post).to receive(:find_by).with({ "something_else" => "55555" }) { post }
end
it "can find the post by the custom primary key" do
expect(resource.find_resource("55555")).to eq post
end
end
context "when using controller finder" do
let(:resource) do
namespace.register(Post) do
controller do
defaults finder: :find_by_title!
end
end
end
after do
Admin.send(:remove_const, :"PostsController")
end
it "can find the post by controller finder" do
allow(Post).to receive(:find_by_title!).with("title-name").and_return(post)
expect(resource.find_resource("title-name")).to eq post
end
end
end
describe "delegation" do
let(:controller) do
Class.new do
def method_missing(name, *args, &block)
"called #{name}"
end
end.new
end
let(:resource) { ActiveAdmin::ResourceDSL.new(double) }
before do
expect(resource).to receive(:controller).and_return(controller)
end
%w[
before_build after_build
before_create after_create
before_update after_update
before_save after_save
before_destroy after_destroy
skip_before_action skip_around_action skip_after_action
append_before_action append_around_action append_after_action
prepend_before_action prepend_around_action prepend_after_action
before_action around_action after_action
actions
].each do |method|
it "delegates #{method}" do
expect(resource.send(method)).to eq "called #{method}"
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_controller_spec.rb | spec/unit/resource_controller_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::ResourceController, type: :controller do
let(:controller) { Admin::PostsController.new }
describe "callbacks" do
around do |example|
with_resources_during(example) do
ActiveAdmin.register(Post) do
after_build :call_after_build
before_save :call_before_save
after_save :call_after_save
before_create :call_before_create
after_create :call_after_create
before_update :call_before_update
after_update :call_after_update
before_destroy :call_before_destroy
after_destroy :call_after_destroy
controller do
private
def call_after_build(obj); end
def call_before_save(obj); end
def call_after_save(obj); end
def call_before_create(obj); end
def call_after_create(obj); end
def call_before_update(obj); end
def call_after_update(obj); end
def call_before_destroy(obj); end
def call_after_destroy(obj); end
end
end
end
end
describe "performing create" do
let(:resource) { double("Resource", save: true) }
before do
expect(resource).to receive(:save)
end
it "should call the before create callback" do
expect(controller).to receive(:call_before_create).with(resource)
controller.send :create_resource, resource
end
it "should call the before save callback" do
expect(controller).to receive(:call_before_save).with(resource)
controller.send :create_resource, resource
end
it "should call the after save callback" do
expect(controller).to receive(:call_after_save).with(resource)
controller.send :create_resource, resource
end
it "should call the after create callback" do
expect(controller).to receive(:call_after_create).with(resource)
controller.send :create_resource, resource
end
end
describe "performing update" do
let(:resource) { double("Resource", :attributes= => true, save: true) }
let(:attributes) { [{}] }
before do
expect(resource).to receive(:attributes=).with(attributes[0])
expect(resource).to receive(:save)
end
it "should call the before update callback" do
expect(controller).to receive(:call_before_update).with(resource)
controller.send :update_resource, resource, attributes
end
it "should call the before save callback" do
expect(controller).to receive(:call_before_save).with(resource)
controller.send :update_resource, resource, attributes
end
it "should call the after save callback" do
expect(controller).to receive(:call_after_save).with(resource)
controller.send :update_resource, resource, attributes
end
it "should call the after create callback" do
expect(controller).to receive(:call_after_update).with(resource)
controller.send :update_resource, resource, attributes
end
end
describe "performing destroy" do
let(:resource) { double("Resource", destroy: true) }
before do
expect(resource).to receive(:destroy)
end
it "should call the before destroy callback" do
expect(controller).to receive(:call_before_destroy).with(resource)
controller.send :destroy_resource, resource
end
it "should call the after destroy callback" do
expect(controller).to receive(:call_after_destroy).with(resource)
controller.send :destroy_resource, resource
end
end
end
describe "action methods" do
around do |example|
with_resources_during(example) do
load_resources { ActiveAdmin.register Post }
end
end
it "should have actual action methods" do
controller.class.clear_action_methods! # make controller recalculate :action_methods on the next call
expect(controller.action_methods.sort).to eq ["batch_action", "create", "destroy", "edit", "index", "new", "show", "update"]
end
end
describe "resource update" do
let(:controller) { Admin::CompaniesController.new }
around do |example|
with_resources_during(example) do
ActiveAdmin.register Company
end
end
it "should not update habtm associations when the resource validation fails" do
resource = Company.create! name: "my company", stores: [Store.create!(name: "store 1")]
controller.send(:update_resource, resource, [{ name: "", store_ids: [] }])
expect(resource.reload.stores).not_to be_empty
end
end
end
RSpec.describe "A specific resource controller", type: :controller do
around do |example|
with_resources_during(example) do
ActiveAdmin.register Post
@controller = Admin::PostsController.new
end
end
describe "authenticating the user" do
it "should do nothing when no authentication_method set" do
namespace = controller.class.active_admin_config.namespace
expect(namespace).to receive(:authentication_method).once.and_return(nil)
controller.send(:authenticate_active_admin_user)
end
it "should call the authentication_method when set" do
namespace = controller.class.active_admin_config.namespace
expect(namespace).to receive(:authentication_method).twice.
and_return(:authenticate_admin_user!)
expect(controller).to receive(:authenticate_admin_user!).and_return(true)
controller.send(:authenticate_active_admin_user)
end
end
describe "retrieving the current user" do
it "should return nil when no current_user_method set" do
namespace = controller.class.active_admin_config.namespace
expect(namespace).to receive(:current_user_method).once.and_return(nil)
expect(controller.send(:current_active_admin_user)).to eq nil
end
it "should call the current_user_method when set" do
user = double
namespace = controller.class.active_admin_config.namespace
expect(namespace).to receive(:current_user_method).twice.
and_return(:current_admin_user)
expect(controller).to receive(:current_admin_user).and_return(user)
expect(controller.send(:current_active_admin_user)).to eq user
end
end
describe "retrieving the resource" do
let(:post) { Post.new title: "An incledibly unique Post Title" }
let(:http_params) { { id: "1" } }
before do
allow(Post).to receive(:find).and_return(post)
controller.class_eval { public :resource }
allow(controller).to receive(:params).and_return(ActionController::Parameters.new(http_params))
end
subject { controller.resource }
it "returns a Post" do
expect(subject).to be_kind_of(Post)
end
context "with a decorator" do
let(:config) { controller.class.active_admin_config }
context "with a Draper decorator" do
before { config.decorator_class_name = "::PostDecorator" }
it "returns a PostDecorator" do
expect(subject).to be_kind_of(PostDecorator)
end
it "returns a PostDecorator that wraps the post" do
expect(subject.title).to eq post.title
end
end
context "with a PORO decorator" do
before { config.decorator_class_name = "::PostPoroDecorator" }
it "returns a PostDecorator" do
expect(subject).to be_kind_of(PostPoroDecorator)
end
it "returns a PostDecorator that wraps the post" do
expect(subject.title).to eq post.title
end
end
end
end
describe "retrieving the resource collection" do
let(:config) { controller.class.active_admin_config }
before do
Post.create!(title: "An incledibly unique Post Title")
config.decorator_class_name = nil
request = double "Request", format: "application/json"
allow(controller).to receive(:params) { {} }
allow(controller).to receive(:request) { request }
end
subject { controller.send :collection }
it {
is_expected.to be_a ActiveRecord::Relation
}
it "returns a collection of posts" do
expect(subject.first).to be_kind_of(Post)
end
context "with a decorator" do
before { config.decorator_class_name = "PostDecorator" }
it "returns a collection decorator using PostDecorator" do
expect(subject).to be_a Draper::CollectionDecorator
expect(subject.decorator_class).to eq PostDecorator
end
it "returns a collection decorator that wraps the post" do
expect(subject.first.title).to eq Post.first.title
end
end
end
describe "performing batch_action" do
let(:batch_action) { ActiveAdmin::BatchAction.new(*batch_action_args, &batch_action_block) }
let(:batch_action_block) { proc { self.instance_variable_set :@block_context, self.class } }
let(:params) { ActionController::Parameters.new(http_params) }
before do
allow(controller.class.active_admin_config).to receive(:batch_actions).and_return([batch_action])
allow(controller).to receive(:params) { params }
end
describe "when params batch_action matches existing BatchAction" do
let(:batch_action_args) { [:flag, "Flag"] }
let(:http_params) do
{ batch_action: "flag", collection_selection: ["1"] }
end
it "should call the block with args" do
expect(controller).to receive(:instance_exec).with(["1"], {})
controller.batch_action
end
it "should call the block in controller scope" do
controller.batch_action
expect(controller.instance_variable_get(:@block_context)).to eq Admin::PostsController
end
end
describe "when params batch_action matches existing BatchAction and form inputs defined" do
let(:batch_action_args) { [:flag, "Flag"] }
let(:http_params) do
{ batch_action: "flag", collection_selection: ["1"], batch_action_inputs: '{ "a": "1", "b": "2" }' }
end
it "should include params" do
expect(controller).to receive(:instance_exec).with(["1"], { "a" => "1", "b" => "2" })
controller.batch_action
end
end
describe "when params batch_action doesn't match a BatchAction" do
let(:batch_action_args) { [:flag, "Flag"] }
let(:http_params) do
{ batch_action: "derp", collection_selection: ["1"] }
end
it "should raise an error" do
expect do
controller.batch_action
end.to raise_error("Couldn't find batch action \"derp\"")
end
end
describe "when params batch_action is blank" do
let(:batch_action_args) { [:flag, "Flag"] }
let(:http_params) do
{ collection_selection: ["1"] }
end
it "should raise an error" do
expect do
controller.batch_action
end.to raise_error("Couldn't find batch action \"\"")
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/async_count_spec.rb | spec/unit/async_count_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::AsyncCount do
include ActiveAdmin::IndexHelper
def seed_posts
[1, 2].map do |i|
Post.create!(title: "Test #{i}", author_id: i * 100)
end
end
it "can be passed to the collection_size helper", if: Post.respond_to?(:async_count) do
seed_posts
expect(collection_size(described_class.new(Post.all))).to eq(Post.count)
expect(collection_size(described_class.new(Post.group(:author_id)))).to eq(Post.distinct.pluck(:author_id).size)
end
describe "#initialize" do
let(:collection) { Post.all }
it "initiates an async_count query", if: Post.respond_to?(:async_count) do
expect(collection).to receive(:async_count)
described_class.new(collection)
end
it "raises an error when ActiveRecord async_count is unavailable", unless: Post.respond_to?(:async_count) do
expect do
described_class.new(collection)
end.to raise_error(ActiveAdmin::AsyncCount::NotSupportedError, %r{does not support :async_count})
end
end
describe "#count", if: Post.respond_to?(:async_count) do
before { seed_posts }
it "returns the result of a count query" do
async_count = described_class.new(Post.all)
expect(async_count.count).to eq(Post.count)
end
it "returns the Hash of counts for a grouped query" do
async_count = described_class.new(Post.group(:author_id))
expect(async_count.count).to eq(100 => 1, 200 => 1)
end
# See https://github.com/rails/rails/issues/50776
it "works around a Rails 7.1.3 bug with wrapped promises" do
promise = instance_double(ActiveRecord::Promise, value: Post.count)
promise_wrapper = instance_double(ActiveRecord::Promise, value: promise)
collection = class_double(Post, async_count: promise_wrapper)
expect(collection).to receive(:except).and_return(collection)
expect(described_class.new(collection).count).to eq(Post.count)
end
end
describe "delegation", if: Post.respond_to?(:async_count) do
let(:collection) { Post.all }
%i[
except
group_values
length
limit_value
].each do |method|
it "delegates #{method}" do
allow(collection).to receive(method).and_call_original
async_count = described_class.new(collection)
async_count.public_send(method)
expect(collection).to have_received(method).at_least(:once)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/component_spec.rb | spec/unit/component_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Component do
let(:component_class) { Class.new(described_class) }
let(:component) { component_class.new }
it "should be a subclass of an html div" do
expect(ActiveAdmin::Component.ancestors).to include(Arbre::HTML::Div)
end
it "should render to a div, even as a subclass" do
expect(component.tag_name).to eq "div"
end
it "should not have a CSS class name by default" do
expect(component.class_list.empty?).to eq true
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/batch_actions/settings_spec.rb | spec/unit/batch_actions/settings_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Batch Actions Settings" do
let(:app) { ActiveAdmin::Application.new }
let(:ns) { ActiveAdmin::Namespace.new(app, "Admin") }
let(:post_resource) { ns.register Post }
it "should be disabled globally by default" do
# Note: the default initializer would set it to true
expect(app.batch_actions).to eq false
expect(ns.batch_actions).to eq false
expect(post_resource.batch_actions_enabled?).to eq false
end
it "should be settable to true" do
app.batch_actions = true
expect(app.batch_actions).to eq true
end
it "should be an inheritable_setting" do
app.batch_actions = true
expect(ns.batch_actions).to eq true
end
it "should be settable at the namespace level" do
app.batch_actions = true
ns.batch_actions = false
expect(app.batch_actions).to eq true
expect(ns.batch_actions).to eq false
end
it "should be settable at the resource level" do
expect(post_resource.batch_actions_enabled?).to eq false
post_resource.batch_actions = true
expect(post_resource.batch_actions_enabled?).to eq true
end
it "should inherit the setting on the resource from the namespace" do
ns.batch_actions = false
expect(post_resource.batch_actions_enabled?).to eq false
expect(post_resource.batch_actions).to be_empty
post_resource.batch_actions = true
expect(post_resource.batch_actions_enabled?).to eq true
expect(post_resource.batch_actions).to_not be_empty
end
it "should inherit the setting from the namespace when set to nil" do
ns.batch_actions = true
post_resource.batch_actions = true
expect(post_resource.batch_actions_enabled?).to eq true
expect(post_resource.batch_actions).to_not be_empty
post_resource.batch_actions = nil
expect(post_resource.batch_actions_enabled?).to eq true # inherited from namespace
expect(post_resource.batch_actions).to_not be_empty
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/batch_actions/resource_spec.rb | spec/unit/batch_actions/resource_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::BatchActions::ResourceExtension do
let(:resource) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.batch_actions = true
namespace.register(Post)
end
describe "default action" do
it "should have the default action by default" do
expect(resource.batch_actions.size).to eq 1
expect(resource.batch_actions.first.sym == :destroy).to eq true
end
end
describe "adding a new batch action" do
before do
resource.clear_batch_actions!
resource.add_batch_action :flag, "Flag" do
# Empty
end
end
it "should add an batch action" do
expect(resource.batch_actions.size).to eq 1
end
it "should store an instance of BatchAction" do
expect(resource.batch_actions.first).to be_an_instance_of(ActiveAdmin::BatchAction)
end
it "should store the block in the batch action" do
expect(resource.batch_actions.first.block).to_not eq nil
end
end
describe "removing batch action" do
before do
resource.remove_batch_action :destroy
end
it "should allow for batch action removal" do
expect(resource.batch_actions.size).to eq 0
end
end
describe "#display_if_block" do
it "should return true by default" do
action = ActiveAdmin::BatchAction.new :default, "Default"
expect(action.display_if_block.call).to eq true
end
it "should return the :if block if set" do
action = ActiveAdmin::BatchAction.new :with_block, "With Block", if: proc { false }
expect(action.display_if_block.call).to eq false
end
end
describe "batch action priority" do
it "should have a default priority" do
action = ActiveAdmin::BatchAction.new :default, "Default"
expect(action.priority).to eq 10
end
it "should correctly order two actions" do
priority_one = ActiveAdmin::BatchAction.new :one, "One", priority: 1
priority_ten = ActiveAdmin::BatchAction.new :ten, "Ten", priority: 10
expect(priority_one).to be < priority_ten
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/ordering_spec.rb | spec/unit/resource/ordering_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Ordering" do
describe "#order_by" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
let(:dsl) { ActiveAdmin::ResourceDSL.new(resource_config) }
it "should register the ordering in the config" do
dsl.run_registration_block do
order_by(:age, &:to_sql)
end
expect(resource_config.ordering.size).to eq(1)
end
it "should allow to setup custom ordering class" do
MyOrderClause = Class.new(ActiveAdmin::OrderClause)
dsl.run_registration_block do
config.order_clause = MyOrderClause
end
expect(resource_config.order_clause).to eq(MyOrderClause)
expect(application.order_clause).to eq(ActiveAdmin::OrderClause)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/action_items_spec.rb | spec/unit/resource/action_items_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource::ActionItems do
let(:resource) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.register(Post)
end
describe "adding a new action item" do
before do
resource.clear_action_items!
resource.add_action_item :empty do
# Empty ...
end
end
it "should add an action item" do
expect(resource.action_items.size).to eq 1
end
it "should store an instance of ActionItem" do
expect(resource.action_items.first).to be_an_instance_of(ActiveAdmin::ActionItem)
end
it "should store the block in the action item" do
expect(resource.action_items.first.block).to_not eq nil
end
it "should be ordered by priority" do
resource.add_action_item :first, priority: 0 do
# Empty ...
end
resource.add_action_item :some_other do
# Empty ...
end
resource.add_action_item :second, priority: 1 do
# Empty ...
end
expect(resource.action_items_for(:index).collect(&:name)).to eq [:first, :second, :empty, :some_other]
end
end
describe "setting an action item to only display on specific controller actions" do
before do
resource.clear_action_items!
resource.add_action_item :new, only: :index do
raise StandardError
end
resource.add_action_item :edit, only: :show do
# Empty ...
end
end
it "should return only relevant action items" do
expect(resource.action_items_for(:index).size).to eq 1
expect do
resource.action_items_for(:index).first.call
end.to raise_exception(StandardError)
end
end
describe "default action items" do
it "should have 3 action items" do
expect(resource.action_items.size).to eq 3
end
it "can be removed by name" do
resource.remove_action_item :new
expect(resource.action_items.size).to eq 2
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/naming_spec.rb | spec/unit/resource/naming_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Naming" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { Namespace.new(application, :admin) }
def config(options = {})
@config ||= Resource.new(namespace, Category, options)
end
module ::Mock class Resource < ActiveRecord::Base; end; end
describe "singular resource name" do
context "when class" do
it "should be the underscored singular resource name" do
expect(config.resource_name.singular).to eq "category"
end
end
context "when a class in a module" do
it "should underscore the module and the class" do
expect(Resource.new(namespace, Mock::Resource).resource_name.singular).to eq "mock_resource"
end
end
context "when you pass the 'as' option" do
it "should underscore the passed through string" do
expect(config(as: "Blog Category").resource_name.singular).to eq "blog_category"
end
end
end
describe "resource label" do
it "should return a pretty name" do
expect(config.resource_label).to eq "Category"
end
it "should return the plural version" do
expect(config.plural_resource_label).to eq "Categories"
end
context "when the :as option is given" do
it "should return the custom name" do
expect(config(as: "My Category").resource_label).to eq "My Category"
end
end
context "when a class in a module" do
it "should include the module and the class" do
expect(Resource.new(namespace, Mock::Resource).resource_label).to eq "Mock Resource"
end
it "should include the module and the pluralized class" do
expect(Resource.new(namespace, Mock::Resource).plural_resource_label).to eq "Mock Resources"
end
end
describe "I18n integration" do
describe "singular label" do
it "should return the titleized model_name.human" do
expect(config.resource_name).to receive(:translate).and_return "Da category"
expect(config.resource_label).to eq "Da category"
end
end
describe "plural label" do
it "should return the titleized plural version defined by i18n if available" do
expect(config.resource_name).to receive(:translate).at_least(:once).and_return "Da categories"
expect(config.plural_resource_label).to eq "Da categories"
end
end
describe "plural label with not default locale" do
it "should return the titleized plural version defined by i18n with custom :count if available" do
expect(config.resource_name).to receive(:translate).at_least(:once).and_return "Категории"
expect(config.plural_resource_label(count: 3)).to eq "Категории"
end
end
context "when the :as option is given" do
describe "singular label" do
it "should translate the custom name" do
config = config(as: "My Category")
expect(config.resource_name).to receive(:translate).and_return "Translated category"
expect(config.resource_label).to eq "Translated category"
end
end
describe "plural label" do
it "should translate the custom name" do
config = config(as: "My Category")
expect(config.resource_name).to receive(:translate).at_least(:once).and_return "Translated categories"
expect(config.plural_resource_label).to eq "Translated categories"
end
end
end
end
end
describe "duplicate resource names" do
let(:resource_name) { config.resource_name }
let(:duplicate_resource_name) { Resource.new(namespace, Category).resource_name }
[:==, :===, :eql?].each do |method|
it "are equivalent when compared with #{method}" do
expect(resource_name.public_send(method, duplicate_resource_name)).to eq true
end
end
it "have identical hash values" do
expect(resource_name.hash).to eq duplicate_resource_name.hash
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.