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
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/importmap.rails_admin.rb
spec/dummy_app/config/importmap.rails_admin.rb
# frozen_string_literal: true # Pin npm packages by running ./bin/importmap pin 'rails_admin', preload: true pin 'rails_admin/src/rails_admin/base', to: 'rails_admin/base.js' pin '@hotwired/turbo', to: 'https://ga.jspm.io/npm:@hotwired/turbo@7.1.0/dist/turbo.es2017-esm.js' pin '@hotwired/turbo-rails', to: 'https://ga.jspm.io/npm:@hotwired/turbo-rails@7.1.3/app/javascript/turbo/index.js' pin '@popperjs/core', to: 'https://ga.jspm.io/npm:@popperjs/core@2.11.5/dist/esm/popper.js' pin '@rails/actioncable/src', to: 'https://ga.jspm.io/npm:@rails/actioncable@7.0.3-1/src/index.js' pin '@rails/actiontext', to: 'https://ga.jspm.io/npm:@rails/actiontext@7.0.3-1/app/javascript/actiontext/index.js' pin '@rails/activestorage', to: 'https://ga.jspm.io/npm:@rails/activestorage@7.0.3-1/app/assets/javascripts/activestorage.esm.js' pin '@rails/ujs', to: 'https://ga.jspm.io/npm:@rails/ujs@7.0.3-1/lib/assets/compiled/rails-ujs.js' pin 'bootstrap', to: 'https://ga.jspm.io/npm:bootstrap@5.1.3/dist/js/bootstrap.esm.js' pin 'flatpickr', to: 'https://ga.jspm.io/npm:flatpickr@4.6.13/dist/flatpickr.js' pin 'flatpickr/', to: 'https://ga.jspm.io/npm:flatpickr@4.6.13/' pin 'jquery', to: 'https://ga.jspm.io/npm:jquery@3.6.0/dist/jquery.js' pin 'jquery-ui/', to: 'https://ga.jspm.io/npm:jquery-ui@1.13.1/' pin 'trix', to: 'https://ga.jspm.io/npm:trix@2.0.0-beta.0/dist/trix.js'
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/boot.rb
spec/dummy_app/config/boot.rb
# frozen_string_literal: true CI_ORM = (ENV['CI_ORM'] || :active_record).to_sym unless defined?(CI_ORM) CI_TARGET_ORMS = %i[active_record mongoid].freeze CI_ASSET = (ENV['CI_ASSET'] || :sprockets).to_sym unless defined?(CI_ASSET) ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile.
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/filter_parameter_logging.rb
spec/dummy_app/config/initializers/filter_parameter_logging.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/application_controller_renderer.rb
spec/dummy_app/config/initializers/application_controller_renderer.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # )
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/session_store.rb
spec/dummy_app/config/initializers/session_store.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_dummy_app_session'
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/devise.rb
spec/dummy_app/config/initializers/devise.rb
# frozen_string_literal: true # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = '5c72fe9ca98a9862e235c7fb8277e3f6a02d41e0f941beebaa5271a712c46da90f5e4a04fde095d7f2f219cd41ec014c72d995837424164ae7ffc0f44eaa3742' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require "devise/orm/#{CI_ORM}" # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:token]` will # enable it only for token authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # :token = Support basic authentication with token authentication key # :token_options = Support token authentication with options as defined in # http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html # config.http_authenticatable = false # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # :http_auth and :token_auth by adding those symbols to the array below. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = 'db4c2356895fab849584ee71a3467a20720ff9b629f27a0da70bd4176773c5360e25d453f1801c69e2e0e61f3a9b5631cda52d7da99b4ced83ea66940db3ce0e' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed new email is stored in # unconfirmed email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. Default is 8..128. config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Configuration for :token_authenticatable # Defines name of the authentication token params key # config.token_authentication_key = :auth_token # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/mongoid.rb
spec/dummy_app/config/initializers/mongoid.rb
# frozen_string_literal: true if CI_ORM == :mongoid filename = if Mongoid.respond_to?(:belongs_to_required_by_default=) 'mongoid6.yml' else 'mongoid5.yml' end ::Mongoid.load!(Rails.root.join('config', filename)) end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/wrap_parameters.rb
spec/dummy_app/config/initializers/wrap_parameters.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/inflections.rb
spec/dummy_app/config/initializers/inflections.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/session_patch.rb
spec/dummy_app/config/initializers/session_patch.rb
# frozen_string_literal: true require 'action_dispatch/middleware/session/abstract_store' # When ORM was switched, but another ORM's model class still exists in session # (Devise saves User model to session), ActionDispatch raises ActionDispatch::Session::SessionRestoreError # and app can't be started unless you delete your browser's cookie data. # To prevent this situation, detect this problem here and reset session data # so user can make another login via Devise. ActionDispatch::Session::StaleSessionCheck.module_eval do def stale_session_check! yield rescue ArgumentError {} end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/rails_admin.rb
spec/dummy_app/config/initializers/rails_admin.rb
# frozen_string_literal: true RailsAdmin.config do |c| c.asset_source = CI_ASSET c.model Team do include_all_fields field :color, :hidden end if Rails.env.production? # Live demo configuration c.main_app_name = ['RailsAdmin', 'Live Demo'] c.included_models = %w[Comment Division Draft Fan FieldTest League NestedFieldTest Player Team User] c.model 'FieldTest' do configure :paperclip_asset do visible false end end c.model 'League' do configure :players do visible false end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/cookies_serializer.rb
spec/dummy_app/config/initializers/cookies_serializer.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # This is a new Rails 5.0 default, so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/shrine.rb
spec/dummy_app/config/initializers/shrine.rb
# frozen_string_literal: true require 'shrine' require 'shrine/storage/memory' Shrine.storages = { cache: Shrine::Storage::Memory.new, store: Shrine::Storage::Memory.new, }
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/assets.rb
spec/dummy_app/config/initializers/assets.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' if Rails.application.config.respond_to?(:assets) # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path Rails.application.config.assets.paths << Rails.root.join('node_modules/@fortawesome/fontawesome-free/webfonts') if Rails.application.config.respond_to?(:assets) # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js )
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/dragonfly.rb
spec/dummy_app/config/initializers/dragonfly.rb
# frozen_string_literal: true require 'dragonfly' # Logger Dragonfly.logger = Rails.logger # Configure Dragonfly.app.configure do plugin :imagemagick protect_from_dos_attacks true secret '904547b2be647f0e11a76933b3220d6bd2fb83f380ac760125e4daa3b9504b4e' url_format '/media/:job/:name' datastore(:file, root_path: Rails.root.join('public/system/dragonfly', Rails.env), server_root: Rails.root.join('public')) end # Mount as middleware Rails.application.middleware.use Dragonfly::Middleware
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/backtrace_silencers.rb
spec/dummy_app/config/initializers/backtrace_silencers.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/mime_types.rb
spec/dummy_app/config/initializers/mime_types.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/secret_token.rb
spec/dummy_app/config/initializers/secret_token.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. DummyApp::Application.config.secret_key_base = '11cefe91820bbc7c4ef81114d5b8e9237bce9c1d5d1b4a2f8b333e151dfa3ff43b3db8d0d3b4dc414f15113f28c5d779e829c3cb3fbcdc7c5a94fe7fdcb2c81c'
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/initializers/cors.rb
spec/dummy_app/config/initializers/cors.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Avoid CORS issues when API is called from the frontend app. # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. # Read more: https://github.com/cyu/rack-cors # Rails.application.config.middleware.insert_before 0, Rack::Cors do # allow do # origins 'example.com' # # resource '*', # headers: :any, # methods: [:get, :post, :put, :patch, :delete, :options, :head] # end # end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/environments/test.rb
spec/dummy_app/config/environments/test.rb
# frozen_string_literal: true DummyApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. if config.respond_to?(:public_file_server) config.public_file_server.enabled = true config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} else config.serve_static_files = true config.static_cache_control = 'public, max-age=3600' end # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = Rails.gem_version >= Gem::Version.new('7.1') ? :none : false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/environments/development.rb
spec/dummy_app/config/environments/development.rb
# frozen_string_literal: true DummyApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = {'Cache-Control' => 'public, max-age=172800'} else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load if CI_ORM == :active_record if config.respond_to?(:assets) # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true end # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. # config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/dummy_app/config/environments/production.rb
spec/dummy_app/config/environments/production.rb
# frozen_string_literal: true DummyApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? config.static_cache_control = 'public, max-age=31536000' # Compress JavaScripts and CSS. # config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Action Cable endpoint configuration # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :request_id ] # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "dummy_app_#{Rails.env}" # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Disable yjit to save memory. config.yjit = false end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/support/fixtures.rb
spec/support/fixtures.rb
# frozen_string_literal: true def file_path(*paths) File.expand_path(File.join(File.dirname(__FILE__), '../fixtures', *paths)) end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/support/cuprite_logger.rb
spec/support/cuprite_logger.rb
# frozen_string_literal: true class ConsoleLogger def self.puts(message) warn(message) unless message.start_with?(' ◀', "\n\n▶") end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/support/fakeio.rb
spec/support/fakeio.rb
# frozen_string_literal: true require 'forwardable' require 'stringio' class FakeIO attr_reader :original_filename, :content_type def initialize(content, filename: nil, content_type: nil) @io = StringIO.new(content) @original_filename = filename @content_type = content_type end extend Forwardable delegate %i[read rewind eof? close size] => :@io end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/rails_admin_spec.rb
spec/integration/rails_admin_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin, type: :request do subject { page } before do RailsAdmin::Config.authenticate_with { warden.authenticate! scope: :user } RailsAdmin::Config.current_user_method(&:current_user) login_as User.create( email: 'username@example.com', password: 'password', ) end # A common mistake for translators is to forget to change the YAML file's # root key from en to their own locale (as people tend to use the English # file as template for a new translation). describe 'localization' do it 'defaults to English' do RailsAdmin.config.included_models = [] visit dashboard_path is_expected.to have_content('Site Administration') is_expected.to have_content('Dashboard') end end describe 'html head' do before { visit dashboard_path } # NOTE: the [href^="/asset... syntax matches the start of a value. The reason # we just do that is to avoid being confused by rails' asset_ids. it 'loads stylesheets in header' do case RailsAdmin.config.asset_source when :sprockets is_expected.to have_selector('head link[href^="/assets/rails_admin"][href$=".css"]', visible: false) when :webpacker is_expected.to have_no_selector('head link[href~="rails_admin"][href$=".css"]', visible: false) end end it 'loads javascript files in body' do case RailsAdmin.config.asset_source when :sprockets is_expected.to have_selector('head script[src^="/assets/rails_admin"][src$=".js"]', visible: false) when :webpacker is_expected.to have_selector('head script[src^="/packs-test/js/rails_admin"][src$=".js"]', visible: false) end end end describe 'custom theming' do before { visit dashboard_path } if CI_ASSET == :sprockets it 'applies the style overridden by assets in the application', js: true do expect(find('.navbar-brand small').style('opacity')).to eq({'opacity' => '0.99'}) end end end describe 'navbar css class' do it 'is set by default' do expect(RailsAdmin.config.navbar_css_classes).to eq(%w[navbar-dark bg-primary border-bottom]) end it 'can be configured' do RailsAdmin.config do |config| config.navbar_css_classes = %w[navbar-light border-bottom] end visit dashboard_path is_expected.to have_css('nav.navbar.navbar-light.border-bottom') end end describe 'sidebar navigation', js: true do it 'is collapsible' do visit dashboard_path is_expected.to have_css('.sidebar .nav-link', text: 'Players') click_button 'Navigation' is_expected.to have_css('.sidebar .btn-toggle.collapsed') is_expected.not_to have_css('.sidebar #navigation.show') is_expected.not_to have_css('.sidebar .nav-link', text: 'Players') end it 'persists over a page transition' do visit dashboard_path click_button 'Navigation' is_expected.to have_css('.sidebar .btn-toggle.collapsed') is_expected.not_to have_css('.sidebar #navigation.show') find('.player_links .show a').trigger('click') is_expected.to have_content 'List of Players' is_expected.not_to have_css('.sidebar .nav-link', text: 'Players') end end describe '_current_user' do # https://github.com/railsadminteam/rails_admin/issues/549 it 'is accessible from the list view' do RailsAdmin.config Player do list do field :name do visible do bindings[:view]._current_user.email == 'username@example.com' end end field :team do visible do bindings[:view]._current_user.email == 'foo@example.com' end end end end visit index_path(model_name: 'player') is_expected.to have_selector('.header.name_field') is_expected.not_to have_selector('.header.team_field') end end describe 'secondary navigation' do it 'has Gravatar image' do visit dashboard_path is_expected.to have_selector('ul.navbar-nav img[src*="gravatar.com"]') end it "does not show Gravatar when user doesn't have email method" do allow_any_instance_of(User).to receive(:respond_to?).and_return(true) allow_any_instance_of(User).to receive(:respond_to?).with(:email).and_return(false) allow_any_instance_of(User).to receive(:respond_to?).with(:devise_scope).and_return(false) visit dashboard_path is_expected.not_to have_selector('ul.nav.pull-right li img') end it 'does not cause error when email is nil' do allow_any_instance_of(User).to receive(:email).and_return(nil) visit dashboard_path is_expected.to have_selector('body.rails_admin') end it 'shows a log out link' do visit dashboard_path is_expected.to have_content 'Log out' end it 'has bg-danger class on log out link' do visit dashboard_path is_expected.to have_selector('.bg-danger') end it 'has links for actions which are marked as show_in_navigation' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_navigation: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_navigation false end root :shown_in_navigation, :dashboard do action_name :dashboard show_in_navigation true end end end visit dashboard_path is_expected.not_to have_css '.root_links li', text: 'Dashboard' is_expected.to have_css '.root_links li', text: 'Look this' end end describe 'CSRF protection' do before do allow_any_instance_of(ActionController::Base).to receive(:protect_against_forgery?).and_return(true) end it 'is enforced' do visit new_path(model_name: 'league') fill_in 'league[name]', with: 'National league' find('input[name="authenticity_token"]', visible: false).set('invalid token') expect { click_button 'Save' }.to raise_error ActionController::InvalidAuthenticityToken end end describe 'Turbo Drive', js: true do let(:player) { FactoryBot.create :player } it 'does not trigger JS errors by going away from and back to RailsAdmin' do visit show_path(model_name: 'player', id: player.id) click_link 'Show in app' click_link 'Back to admin' is_expected.to have_content 'Details for Player' end it 'triggers rails_admin.dom_ready right after a validation error' do visit edit_path(model_name: 'player', id: player.id) fill_in 'player[name]', with: 'on steroids' find_button('Save').trigger 'click' is_expected.to have_content 'Player failed to be updated' is_expected.to have_css '.filtering-select[data-input-for="player_team_id"]' end it 'does not prefetch pages' do allow_any_instance_of(RailsAdmin::Config::Actions::Index).to receive(:controller).and_raise('index prefetched') visit dashboard_path find('.sidebar a.nav-link[href$="/player"]').hover sleep 0.3 # Turbo waits 100ms before prefetch end end describe 'dom_ready events', js: true do it 'trigger properly' do visit dashboard_path expect(evaluate_script('domReadyTriggered')).to match_array %w[plainjs/dot jquery/dot] end end context 'with invalid model name' do it "redirects to dashboard and inform the user the model wasn't found" do visit '/admin/whatever' expect(page.driver.status_code).to eq(404) expect(find('.alert-danger')).to have_content("Model 'Whatever' could not be found") end end context 'with invalid action' do it "redirects to balls index and inform the user the id wasn't found" do visit '/admin/ball/545-typo' expect(page.driver.status_code).to eq(404) expect(find('.alert-danger')).to have_content("Ball with id '545-typo' could not be found") end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/authorization/cancancan_spec.rb
spec/integration/authorization/cancancan_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin CanCanCan Authorization', type: :request do class Ability include CanCan::Ability def initialize(user) can :access, :rails_admin if user.roles.include? :admin can :read, :dashboard if user.roles.include? :test_exception can :access, :rails_admin can :manage, :all can :show_in_app, :all can %i[update destroy], Player cannot %i[update destroy], Player, retired: true else can :manage, Player if user.roles.include? :manage_player can :read, Player, retired: false if user.roles.include? :read_player can :create, Player, suspended: true if user.roles.include? :create_player can :update, Player, retired: false if user.roles.include? :update_player can :destroy, Player, retired: false if user.roles.include? :destroy_player can :history, Player, retired: false if user.roles.include? :history_player can :show_in_app, Player, retired: false if user.roles.include? :show_in_app_player end end end class AdminAbility include CanCan::Ability def initialize(user) can :access, :rails_admin if user.roles.include? :admin can :show_in_app, :all can :manage, :all end end subject { page } before do RailsAdmin.config do |c| c.authorize_with(:cancancan) c.authenticate_with { warden.authenticate! scope: :user } c.current_user_method(&:current_user) end @player_model = RailsAdmin::AbstractModel.new(Player) @user = FactoryBot.create :user login_as @user end describe 'with no roles' do before do @user.update(roles: []) end it 'GET /admin should raise CanCan::AccessDenied' do expect { visit dashboard_path }.to raise_error(CanCan::AccessDenied) end it 'GET /admin/player should raise CanCan::AccessDenied' do expect { visit index_path(model_name: 'player') }.to raise_error(CanCan::AccessDenied) end end describe 'with read player role' do before do @user.update(roles: %i[admin read_player]) end it 'GET /admin should show Player but not League' do visit dashboard_path is_expected.to have_content('Player') is_expected.not_to have_content('League') is_expected.not_to have_content('Add new') end it 'GET /admin/player should render successfully but not list retired players and not show new, edit, or delete actions' do # ensure :name column to be shown RailsAdmin.config Player do list do field :name end end @players = [ FactoryBot.create(:player, retired: false), FactoryBot.create(:player, retired: true), ] visit index_path(model_name: 'player') is_expected.to have_content(@players[0].name) is_expected.not_to have_content(@players[1].name) is_expected.not_to have_content('Add new') is_expected.to have_css('.show_member_link') is_expected.not_to have_css('.edit_member_link') is_expected.not_to have_css('.delete_member_link') is_expected.not_to have_css('.history_show_member_link') is_expected.not_to have_css('.show_in_app_member_link') end it 'GET /admin/team should raise CanCan::AccessDenied' do expect { visit index_path(model_name: 'team') }.to raise_error(CanCan::AccessDenied) end it 'GET /admin/player/new should raise CanCan::AccessDenied' do expect { visit new_path(model_name: 'player') }.to raise_error(CanCan::AccessDenied) end end describe 'with create and read player role' do before do @user.update(roles: %i[admin read_player create_player]) end it 'GET /admin/player/new should render and create record upon submission' do visit new_path(model_name: 'player') is_expected.not_to have_content('Save and edit') is_expected.not_to have_content('Delete') is_expected.to have_content('Save and add another') fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' click_button 'Save' # first(:button, "Save").click is_expected.not_to have_content('Edit') @player = RailsAdmin::AbstractModel.new('Player').first expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') expect(@player).to be_suspended # suspended is inherited behavior based on permission end it 'POST /admin/player/new with unauthorized attribute value should raise access denied' do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson' choose name: 'player[suspended]', option: '0' expect { click_button 'Save' }.to raise_error(CanCan::AccessDenied) end it 'GET /admin/player/1/edit should raise access denied' do @player = FactoryBot.create :player expect { visit edit_path(model_name: 'player', id: @player.id) }.to raise_error(CanCan::AccessDenied) end end describe 'with update and read player role' do before do @user.update(roles: %i[admin read_player update_player]) end it 'GET /admin/player/1/edit should render and update record upon submission' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) is_expected.to have_content('Save and edit') is_expected.not_to have_content('Save and add another') is_expected.not_to have_content('Add new') is_expected.not_to have_content('Delete') is_expected.not_to have_content('History') is_expected.not_to have_content('Show in app') fill_in 'player[name]', with: 'Jackie Robinson' click_button 'Save' # click_button "Save" # first(:button, "Save").click @player.reload expect(@player.name).to eq('Jackie Robinson') end it 'GET /admin/player/1/edit with retired player should raise access denied' do @player = FactoryBot.create :player, retired: true expect { visit edit_path(model_name: 'player', id: @player.id) }.to raise_error(CanCan::AccessDenied) end it 'PUT /admin/player/new with unauthorized attribute value should raise access denied' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) choose name: 'player[retired]', option: '1' expect { click_button 'Save' }.to raise_error(CanCan::AccessDenied) end it 'GET /admin/player/1/delete should raise access denied' do @player = FactoryBot.create :player expect { visit delete_path(model_name: 'player', id: @player.id) }.to raise_error(CanCan::AccessDenied) end end describe 'with history role' do it 'shows links to history action' do @user.update(roles: %i[admin read_player history_player]) @player = FactoryBot.create :player visit index_path(model_name: 'player') is_expected.to have_css('.show_member_link') is_expected.not_to have_css('.edit_member_link') is_expected.not_to have_css('.delete_member_link') is_expected.to have_css('.history_show_member_link') visit show_path(model_name: 'player', id: @player.id) is_expected.to have_content('Show') is_expected.not_to have_content('Edit') is_expected.not_to have_content('Delete') is_expected.to have_content('History') end end describe 'with show in app role' do it 'shows links to show in app action' do @user.update(roles: %i[admin read_player show_in_app_player]) @player = FactoryBot.create :player visit index_path(model_name: 'player') is_expected.to have_css('.show_member_link') is_expected.not_to have_css('.edit_member_link') is_expected.not_to have_css('.delete_member_link') is_expected.not_to have_css('.history_show_member_link') is_expected.to have_css('.show_in_app_member_link') visit show_path(model_name: 'player', id: @player.id) is_expected.to have_content('Show') is_expected.not_to have_content('Edit') is_expected.not_to have_content('Delete') is_expected.not_to have_content('History') is_expected.to have_content('Show in app') end end describe 'with all roles' do it 'shows links to all actions' do @user.update(roles: %i[admin manage_player]) @player = FactoryBot.create :player visit index_path(model_name: 'player') is_expected.to have_css('.show_member_link') is_expected.to have_css('.edit_member_link') is_expected.to have_css('.delete_member_link') is_expected.to have_css('.history_show_member_link') is_expected.to have_css('.show_in_app_member_link') visit show_path(model_name: 'player', id: @player.id) is_expected.to have_content('Show') is_expected.to have_content('Edit') is_expected.to have_content('Delete') is_expected.to have_content('History') is_expected.to have_content('Show in app') end end describe 'with destroy and read player role' do before do @user.update(roles: %i[admin read_player destroy_player]) end it 'GET /admin/player/1/delete should render and destroy record upon submission' do @player = FactoryBot.create :player player_id = @player.id visit delete_path(model_name: 'player', id: player_id) click_button "Yes, I'm sure" expect(@player_model.get(player_id)).to be_nil end it 'GET /admin/player/1/delete with retired player should raise access denied' do @player = FactoryBot.create :player, retired: true expect { visit delete_path(model_name: 'player', id: @player.id) }.to raise_error(CanCan::AccessDenied) end it 'GET /admin/player/bulk_delete should render records which are authorized to' do active_player = FactoryBot.create :player, retired: false retired_player = FactoryBot.create :player, retired: true post bulk_action_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: [active_player, retired_player].collect(&:id)) expect(response.body).to include(active_player.name) expect(response.body).not_to include(retired_player.name) end it 'POST /admin/player/bulk_destroy should destroy records which are authorized to' do active_player = FactoryBot.create :player, retired: false retired_player = FactoryBot.create :player, retired: true delete bulk_delete_path(model_name: 'player', bulk_ids: [active_player, retired_player].collect(&:id)) expect(@player_model.get(active_player.id)).to be_nil expect(@player_model.get(retired_player.id)).not_to be_nil end end describe 'with exception role' do it 'GET /admin/player/bulk_delete should render records which are authorized to' do @user.update(roles: %i[admin test_exception]) active_player = FactoryBot.create :player, retired: false retired_player = FactoryBot.create :player, retired: true post bulk_action_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: [active_player, retired_player].collect(&:id)) expect(response.body).to include(active_player.name) expect(response.body).not_to include(retired_player.name) end it 'POST /admin/player/bulk_destroy should destroy records which are authorized to' do @user.update(roles: %i[admin test_exception]) active_player = FactoryBot.create :player, retired: false retired_player = FactoryBot.create :player, retired: true delete bulk_delete_path(model_name: 'player', bulk_ids: [active_player, retired_player].collect(&:id)) expect(@player_model.get(active_player.id)).to be_nil expect(@player_model.get(retired_player.id)).not_to be_nil end end describe 'with a custom admin ability' do before do RailsAdmin.config do |c| c.authorize_with :cancancan do ability_class { AdminAbility } end end @user = FactoryBot.create :user login_as @user end describe 'with admin role only' do before do @user.update(roles: [:admin]) end it 'GET /admin/team should render successfully' do visit index_path(model_name: 'team') expect(page.status_code).to eq(200) end it 'GET /admin/player/new should render successfully' do visit new_path(model_name: 'player') expect(page.status_code).to eq(200) end it 'GET /admin/player/1/edit should render successfully' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) expect(page.status_code).to eq(200) end it 'GET /admin/player/1/edit with retired player should render successfully' do @player = FactoryBot.create :player, retired: true visit edit_path(model_name: 'player', id: @player.id) expect(page.status_code).to eq(200) end it 'GET /admin/player/1/delete should render successfully' do @player = FactoryBot.create :player visit delete_path(model_name: 'player', id: @player.id) expect(page.status_code).to eq(200) end it 'GET /admin/player/1/delete with retired player should render successfully' do @player = FactoryBot.create :player, retired: true visit delete_path(model_name: 'player', id: @player.id) expect(page.status_code).to eq(200) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/authorization/pundit_spec.rb
spec/integration/authorization/pundit_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin Pundit Authorization', type: :request do subject { page } before do RailsAdmin.config do |c| c.authorize_with(:pundit) c.authenticate_with { warden.authenticate! scope: :user } c.current_user_method(&:current_user) end @player_model = RailsAdmin::AbstractModel.new(Player) @user = FactoryBot.create :user, roles: [] login_as @user end describe 'with no roles' do it 'GET /admin should raise Pundit::NotAuthorizedError' do expect { visit dashboard_path }.to raise_error(Pundit::NotAuthorizedError) end it 'GET /admin/player should raise Pundit::NotAuthorizedError' do expect { visit index_path(model_name: 'player') }.to raise_error(Pundit::NotAuthorizedError) end end describe 'with read player role' do before do @user.update(roles: %i[admin read_player]) end it 'GET /admin should show Player but not League' do visit dashboard_path is_expected.to have_content('Player') is_expected.not_to have_content('League') is_expected.not_to have_content('Add new') end it 'GET /admin/team should raise Pundit::NotAuthorizedError' do expect { visit index_path(model_name: 'team') }.to raise_error(Pundit::NotAuthorizedError) end it 'GET /admin/player/1/edit should raise access denied' do @player = FactoryBot.create :player expect { visit edit_path(model_name: 'player', id: @player.id) }.to raise_error(Pundit::NotAuthorizedError) end end describe 'with admin role' do before do @user.update(roles: %i[admin manage_player]) end it 'GET /admin should show Player but not League' do visit dashboard_path is_expected.to have_content('Player') end it 'GET /admin/player/new should render and create record upon submission' do visit new_path(model_name: 'player') is_expected.to have_content('Save and edit') is_expected.not_to have_content('Delete') is_expected.to have_content('Save and add another') fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' click_button 'Save' is_expected.not_to have_content('Edit') @player = RailsAdmin::AbstractModel.new('Player').first expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end describe 'with all roles' do it 'shows links to all actions' do @user.update(roles: %i[admin manage_player]) @player = FactoryBot.create :player visit index_path(model_name: 'player') is_expected.to have_css('.show_member_link') is_expected.to have_css('.edit_member_link') is_expected.to have_css('.delete_member_link') is_expected.to have_css('.history_show_member_link') is_expected.to have_css('.show_in_app_member_link') visit show_path(model_name: 'player', id: @player.id) is_expected.to have_content('Show') is_expected.to have_content('Edit') is_expected.to have_content('Delete') is_expected.to have_content('History') is_expected.to have_content('Show in app') end end describe 'with create and read player role' do before do @user.update(roles: %i[admin read_player create_player]) end it 'POST /admin/player/new with unauthorized attribute value should raise access denied' do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson' choose name: 'player[suspended]', option: '0' expect { click_button 'Save' }.to raise_error(Pundit::NotAuthorizedError) end end describe 'with update and read player role' do before do @user.update(roles: %i[admin read_player update_player]) end it 'PUT /admin/player/new with unauthorized attribute value should raise access denied' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) choose name: 'player[retired]', option: '1' expect { click_button 'Save' }.to raise_error(Pundit::NotAuthorizedError) end end context 'when ApplicationController already has pundit_user' do let(:admin) { FactoryBot.create :user, roles: [:admin] } before do RailsAdmin.config.parent_controller = 'ApplicationController' allow_any_instance_of(ApplicationController).to receive(:pundit_user).and_return(admin) end it 'uses original pundit_user' do pending 'no way to dynamically change superclass' expect { visit dashboard_path }.not_to raise_error end end context 'when custom authorization key is set' do before do RailsAdmin.config do |c| c.actions do dashboard index do authorization_key :rails_admin_index end end end end it 'uses the custom key' do expect { visit index_path(model_name: 'team') }.not_to raise_error end end context 'when custom authorization key is suffixed with ?' do before do @user.update(roles: [:admin]) RailsAdmin.config do |c| c.actions do dashboard do authorization_key :dashboard? end index end end end it 'does not append ? on policy check' do expect_any_instance_of(ApplicationPolicy).not_to receive(:'dashboard??') visit dashboard_path end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/authentication/devise_spec.rb
spec/integration/authentication/devise_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin Devise Authentication', type: :request do subject { page } let!(:user) { FactoryBot.create :user } before do RailsAdmin.config do |config| config.authenticate_with do warden.authenticate! scope: :user end config.current_user_method(&:current_user) end end it 'supports logging-in', js: true do visit dashboard_path fill_in 'Email', with: user.email fill_in 'Password', with: 'password' click_button 'Log in' is_expected.to have_css 'body.rails_admin' end it 'supports logging-out', js: true do login_as user visit dashboard_path click_link 'Log out' is_expected.to have_content 'Log in' end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/auditing/paper_trail_spec.rb
spec/integration/auditing/paper_trail_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin PaperTrail auditing', active_record: true do before(:each) do RailsAdmin.config do |config| config.audit_with :paper_trail end end shared_examples :paper_on_object_creation do describe 'on object creation', type: :request do subject { page } before do @user = FactoryBot.create :user RailsAdmin::Config.authenticate_with { warden.authenticate! scope: :user } RailsAdmin::Config.current_user_method(&:current_user) login_as @user with_versioning do visit new_path(model_name: paper_model_name) fill_in paper_field_name, with: 'Jackie Robinson' click_button 'Save' @object = RailsAdmin::AbstractModel.new(paper_class_name).first end end it 'records a version' do expect(@object.versions.size).to eq 1 expect(@object.versions.first.whodunnit).to eq @user.id.to_s end end end shared_examples :paper_history do describe 'model history fetch' do before(:each) do PaperTrail::Version.delete_all @model = RailsAdmin::AbstractModel.new(paper_class_name) @user = FactoryBot.create :user @paper_trail_test = FactoryBot.create(paper_factory) with_versioning do # `PaperTrail.whodunnit` deprecated in PT 9, will be removed in 10. # Use `PaperTrail.request.whodunnit` instead. if PaperTrail.respond_to?(:request) PaperTrail.request.whodunnit = @user.id else PaperTrail.whodunnit = @user.id end 30.times do |i| @paper_trail_test.update!(name: "updated name #{i}") end end end it 'creates versions' do expect(paper_class_name.constantize.version_class_name.constantize.count).to eq(30) end describe 'model history fetch with auditing adapter' do before(:all) do @adapter = RailsAdmin::Extensions::PaperTrail::AuditingAdapter.new(nil) end it 'fetches on page of history' do versions = @adapter.listing_for_model @model, nil, false, false, false, nil, 20 expect(versions.total_count).to eq(30) expect(versions.count).to eq(20) end it 'respects RailsAdmin::Config.default_items_per_page' do RailsAdmin.config.default_items_per_page = 15 versions = @adapter.listing_for_model @model, nil, false, false, false, nil expect(versions.total_count).to eq(30) expect(versions.count).to eq(15) end it 'sets correct next page' do versions = @adapter.listing_for_model @model, nil, false, false, false, 2, 10 expect(versions.next_page).to eq(3) end it 'can fetch all history' do versions = @adapter.listing_for_model @model, nil, false, false, true, nil, 20 expect(versions.total_count).to eq(30) expect(versions.count).to eq(30) end describe 'returned version objects' do before(:each) do @padinated_listing = @adapter.listing_for_model @model, nil, false, false, false, nil @version = @padinated_listing.first end it '#username returns user email' do expect(@version.username).to eq(@user.email) end it '#message returns event' do expect(@version.message).to eq('update') end describe 'changed item attributes' do it '#item returns item.id' do expect(@version.item).to eq(@paper_trail_test.id) end it '#table returns item class name' do expect(@version.table.to_s).to eq(@model.model.base_class.name) end end context 'with Kaminari' do before do Kaminari.config.page_method_name = :per_page_kaminari end after do Kaminari.config.page_method_name = :page end let(:paginated_array) { Kaminari::PaginatableArray.new.page('1') } it "supports pagination when Kaminari's page_method_name is customized" do expect(PaperTrail::Version).to receive(:per_page_kaminari).twice.and_return(@padinated_listing) allow(Kaminari).to receive(:paginate_array).and_return(paginated_array) expect(paginated_array).to receive(:per_page_kaminari).twice.and_return(paginated_array) @adapter.listing_for_model @model, nil, false, false, false, nil @adapter.listing_for_object @model, @paper_trail_test, nil, false, false, false, nil end it "does not break when Kaminari's page_method_name is not applied to Kaminari::PaginatableArray" do expect(PaperTrail::Version).to receive(:per_page_kaminari).twice.and_return(@padinated_listing) allow(Kaminari).to receive(:paginate_array).and_return(paginated_array) allow(paginated_array).to receive(:respond_to).with(:per_page_kaminari).and_return(false) expect(paginated_array).to receive(:page).twice.and_return(paginated_array) @adapter.listing_for_model @model, nil, false, false, false, nil @adapter.listing_for_object @model, @paper_trail_test, nil, false, false, false, nil end end end end end end context 'with a normal PaperTrail model' do let(:paper_class_name) { 'PaperTrailTest' } let(:paper_factory) { :paper_trail_test } it_behaves_like :paper_on_object_creation do let(:paper_model_name) { 'paper_trail_test' } let(:paper_field_name) { 'paper_trail_test[name]' } end it_behaves_like :paper_history end context 'with a subclassed PaperTrail model' do let(:paper_class_name) { 'PaperTrailTestSubclass' } let(:paper_factory) { :paper_trail_test_subclass } it_behaves_like :paper_on_object_creation do let(:paper_model_name) { 'paper_trail_test_subclass' } let(:paper_field_name) { 'paper_trail_test_subclass[name]' } end it_behaves_like :paper_history end context 'with a namespaced PaperTrail model' do let(:paper_class_name) { 'PaperTrailTest::SubclassInNamespace' } let(:paper_factory) { :paper_trail_test_subclass_in_namespace } it_behaves_like :paper_on_object_creation do let(:paper_model_name) { 'paper_trail_test~subclass_in_namespace' } let(:paper_field_name) { 'paper_trail_test_subclass_in_namespace[name]' } end it_behaves_like :paper_history end context 'with a PaperTrail model with custom version association name' do let(:paper_class_name) { 'PaperTrailTestWithCustomAssociation' } let(:paper_factory) { :paper_trail_test_with_custom_association } it_behaves_like :paper_history end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/show_spec.rb
spec/integration/actions/show_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Show action', type: :request do subject { page } let(:team) { FactoryBot.create :team } describe 'page' do it 'has History, Edit, Delete, Details and attributes' do @player = FactoryBot.create :player visit show_path(model_name: 'player', id: @player.id) is_expected.to have_selector('a', text: 'History') is_expected.to have_selector('a', text: 'Edit') is_expected.to have_selector('a', text: 'Delete') is_expected.to have_content('Details') is_expected.to have_content('Name') is_expected.to have_content(@player.name) is_expected.to have_content('Number') is_expected.to have_content(@player.number) end end context 'with invalid id' do it 'raises NotFound' do visit '/admin/players/123this-id-doesnt-exist' expect(page.driver.status_code).to eq(404) end end describe 'JSON show view' do before do @player = FactoryBot.create :player visit uri end let(:uri) { show_path(model_name: 'player', id: @player.id, format: :json) } let(:body) { page.body } it 'creates a JSON uri' do expect(uri).to eq("/admin/player/#{@player.id}.json") end it 'contains the JSONified object' do expect(JSON.parse(body)).to eq JSON.parse @player.reload.to_json end end context 'when compact_show_view is enabled' do it 'hides nil fields in show view by default' do visit show_path(model_name: 'team', id: team.id) is_expected.not_to have_css('.logo_url_field') end it 'hides blank fields in show view by default' do team.update logo_url: '' visit show_path(model_name: 'team', id: team.id) is_expected.not_to have_css('.logo_url_field') end it 'is disactivable' do RailsAdmin.config do |c| c.compact_show_view = false end visit show_path(model_name: 'team', id: team.id) is_expected.to have_css('.logo_url_field') end describe 'with boolean field' do let(:player) { FactoryBot.create :player, retired: false } it 'does not hide false value' do visit show_path(model_name: 'player', id: player.id) is_expected.to have_css('.retired_field') end end end context 'when compact_show_view is disabled' do before do RailsAdmin.config do |c| c.compact_show_view = false end end it 'shows nil fields' do team.update logo_url: nil visit show_path(model_name: 'team', id: team.id) is_expected.to have_css('.logo_url_field') end it 'shows blank fields' do team.update logo_url: '' visit show_path(model_name: 'team', id: team.id) is_expected.to have_css('.logo_url_field') end end describe 'bindings' do it 'should be present' do RailsAdmin.config Team do |_c| show do field :name do show do bindings[:object] && bindings[:view] && bindings[:controller] end end end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('div .name_field.string_type') end end describe 'css hooks' do it 'is present' do visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('div .name_field.string_type') end end describe 'field grouping' do before do RailsAdmin.config do |c| c.compact_show_view = false end end it 'is hideable' do RailsAdmin.config Team do show do group :default do hide end end end visit show_path(model_name: 'team', id: team.id) is_expected.not_to have_selector('h4', text: 'Basic info') %w[ division name logo_url manager ballpark mascot founded wins losses win_percentage revenue ].each do |field| is_expected.not_to have_selector(".#{field}_field") end end it 'hides association groupings by the name of the association' do RailsAdmin.config Team do show do group :players do hide end end end visit show_path(model_name: 'team', id: team.id) is_expected.not_to have_selector('h4', text: 'Players') end it 'is renameable' do RailsAdmin.config Team do show do group :default do label 'Renamed group' end end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('h4', text: 'Renamed group') end it 'has accessor for its fields' do RailsAdmin.config Team do show do group :default do field :name field :logo_url end group :belongs_to_associations do label "Belong's to associations" field :division end end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('h4', text: 'Basic info') is_expected.to have_selector('h4', text: "Belong's to associations") is_expected.to have_selector('.name_field') is_expected.to have_selector('.logo_url_field') is_expected.to have_selector('.division_field') end it 'has accessor for its fields by type' do RailsAdmin.config Team do show do group :default do field :name field :logo_url end group :other do field :division field :manager field :ballpark fields_of_type :string do label { "#{label} (STRING)" } end end end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.card-header', text: 'Name') is_expected.to have_selector('.card-header', text: 'Logo url') is_expected.to have_selector('.card-header', text: 'Division') is_expected.to have_selector('.card-header', text: 'Manager (STRING)') is_expected.to have_selector('.card-header', text: 'Ballpark (STRING)') end end describe 'fields' do before do RailsAdmin.config do |c| c.compact_show_view = false end end it 'shows all by default' do visit show_path(model_name: 'team', id: team.id) %w[ division name logo_url manager ballpark mascot founded wins losses win_percentage revenue players fans ].each do |field| is_expected.to have_selector(".#{field}_field") end end it 'only shows the defined fields and appear in order defined' do RailsAdmin.config Team do show do field :manager field :division field :name end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.manager_field') is_expected.to have_selector('.division_field') is_expected.to have_selector('.name_field') end it 'delegates the label option to the ActiveModel API' do RailsAdmin.config Team do show do field :manager field :fans end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.card-header', text: 'Team Manager') is_expected.to have_selector('.card-header', text: 'Some Fans') end it 'is renameable' do RailsAdmin.config Team do show do field :manager do label 'Renamed field' end field :division field :name end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.card-header', text: 'Renamed field') is_expected.to have_selector('.card-header', text: 'Division') is_expected.to have_selector('.card-header', text: 'Name') end it 'is renameable by type' do RailsAdmin.config Team do show do fields_of_type :string do label { "#{label} (STRING)" } end end end visit show_path(model_name: 'team', id: team.id) [ 'Division', 'Name (STRING)', 'Logo url (STRING)', 'Manager (STRING)', 'Ballpark (STRING)', 'Mascot (STRING)', 'Founded', 'Wins', 'Losses', 'Win percentage', 'Revenue', 'Players', 'Fans' ].each do |text| is_expected.to have_selector('.card-header', text: text) end end it 'is globally renameable by type' do RailsAdmin.config Team do show do fields_of_type :string do label { "#{label} (STRING)" } end end end visit show_path(model_name: 'team', id: team.id) [ 'Division', 'Name (STRING)', 'Logo url (STRING)', 'Manager (STRING)', 'Ballpark (STRING)', 'Mascot (STRING)', 'Founded', 'Wins', 'Losses', 'Win percentage', 'Revenue', 'Players', 'Fans' ].each do |text| is_expected.to have_selector('.card-header', text: text) end end it 'is hideable' do RailsAdmin.config Team do show do field :manager do hide end field :division field :name end end visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.division_field') is_expected.to have_selector('.name_field') end it 'is hideable by type' do RailsAdmin.config Team do show do fields_of_type :string do hide end end end visit show_path(model_name: 'team', id: team.id) ['Name', 'Logo url', 'Manager', 'Ballpark', 'Mascot'].each do |text| is_expected.not_to have_selector('.card-header', text: text) end ['Division', 'Founded', 'Wins', 'Losses', 'Win percentage', 'Revenue', 'Players', 'Fans'].each do |text| is_expected.to have_selector('.card-header', text: text) end end it 'is globally hideable by type' do RailsAdmin.config Team do show do fields_of_type :string do hide end end end visit show_path(model_name: 'team', id: team.id) ['Name', 'Logo url', 'Manager', 'Ballpark', 'Mascot'].each do |text| is_expected.not_to have_selector('.card-header', text: text) end ['Division', 'Founded', 'Wins', 'Losses', 'Win percentage', 'Revenue', 'Players', 'Fans'].each do |text| is_expected.to have_selector('.card-header', text: text) end end end describe 'virtual field' do let(:team) { FactoryBot.create :team, name: 'foobar' } context 'with formatted_value defined' do before do RailsAdmin.config Team do show do field :truncated_name do formatted_value do bindings[:object].name.truncate(5) end end end end end it 'shows up correctly' do visit show_path(model_name: 'team', id: team.id) is_expected.to have_selector('.truncated_name_field') is_expected.to have_selector('.card', text: 'fo...') end end context 'without formatted_value' do before do RailsAdmin.config Team do show do field :truncated_name do pretty_value do bindings[:object].name.truncate(5) end end end end end it 'raises error along with suggestion' do expect { visit show_path(model_name: 'team', id: team.id) }.to raise_error(/you should declare 'formatted_value'/) end end end describe 'with model scope' do let!(:comments) { %w[something anything].map { |content| FactoryBot.create :comment_confirmed, content: content } } before do RailsAdmin.config do |config| config.model Comment::Confirmed do scope { Comment::Confirmed.unscoped } end end end it 'overrides default_scope' do visit show_path(model_name: 'comment~confirmed', id: comments[0].id) is_expected.to have_selector('.card-body', text: 'something') visit show_path(model_name: 'comment~confirmed', id: comments[1].id) is_expected.to have_selector('.card-body', text: 'anything') end end context 'with composite primary keys', composite_primary_keys: true do let(:fanship) { FactoryBot.create(:fanship) } it 'shows the object' do visit show_path(model_name: 'fanship', id: fanship.id) is_expected.to have_link(fanship.fan.name) is_expected.to have_link(fanship.team.name) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/export_spec.rb
spec/integration/actions/export_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'csv' RSpec.describe 'Export action', type: :request do subject { page } let!(:player) { FactoryBot.create(:player) } it 'exports to CSV' do visit export_path(model_name: 'player') click_button 'Export to csv' is_expected.to have_content player.name end it 'exports to JSON' do visit export_path(model_name: 'player') click_button 'Export to json' is_expected.to have_content player.name end it 'exports to XML' do pending "Mongoid does not support to_xml's :include option" if CI_ORM == :mongoid visit export_path(model_name: 'player') click_button 'Export to xml' is_expected.to have_content player.name end it 'works with Turbo Drive enabled', js: true do visit export_path(model_name: 'player') page.execute_script 'console.error = function(error) { throw error }' expect { find_button('Export to csv').trigger('click') }.not_to raise_error end it 'does not break when nothing is checked' do visit export_path(model_name: 'comment') all('input[type="checkbox"]').each(&:uncheck) expect { click_button 'Export to csv' }.not_to raise_error end describe 'with associations' do let!(:players) { FactoryBot.create_list(:player, 3) } let(:team) { FactoryBot.create :team } let(:draft) { FactoryBot.create :draft } let(:comments) { FactoryBot.create_list(:comment, 2) } before do player.team = team player.draft = draft player.comments = comments player.save end it 'exports to CSV with default schema, containing properly translated header and follow configuration' do RailsAdmin.config do |c| c.model Player do include_all_fields field :name do export_value do "#{value} exported" end end field :json_field, :json do formatted_value do '{}' end end end end visit export_path(model_name: 'player') is_expected.to have_content 'Select fields to export' select "<comma> ','", from: 'csv_options_generator_col_sep' click_button 'Export to csv' csv = CSV.parse page.driver.response.body.force_encoding('utf-8') # comes through as us-ascii on some platforms expect(csv[0]).to match_array ['Id', 'Created at', 'Updated at', 'Deleted at', 'Name', 'Position', 'Number', 'Retired', 'Injured', 'Born on', 'Notes', 'Suspended', 'Formation', 'Json field', 'Id [Team]', 'Created at [Team]', 'Updated at [Team]', 'Name [Team]', 'Logo url [Team]', 'Team Manager [Team]', 'Ballpark [Team]', 'Mascot [Team]', 'Founded [Team]', 'Wins [Team]', 'Losses [Team]', 'Win percentage [Team]', 'Revenue [Team]', 'Color [Team]', 'Custom field [Team]', 'Main Sponsor [Team]', 'Id [Draft]', 'Created at [Draft]', 'Updated at [Draft]', 'Date [Draft]', 'Round [Draft]', 'Pick [Draft]', 'Overall [Draft]', 'College [Draft]', 'Notes [Draft]', 'Id [Comments]', 'Content [Comments]', 'Created at [Comments]', 'Updated at [Comments]'] expect(csv.flatten).to include("#{player.name} exported") expect(csv.flatten).to include(player.team.name) expect(csv.flatten).to include(player.draft.college) expect(csv.flatten.join(' ')).to include(player.comments.first.content.split("\n").first.strip) expect(csv.flatten.join(' ')).to include(player.comments.second.content.split("\n").first.strip) end let(:custom_schema) do # removed schema=>only=>created_at { 'only' => [PK_COLUMN.to_s, 'updated_at', 'deleted_at', 'name', 'position', 'number', 'retired', 'injured', 'born_on', 'notes', 'suspended'], 'include' => { 'team' => {'only' => [PK_COLUMN.to_s, 'created_at', 'updated_at', 'name', 'logo_url', 'manager', 'ballpark', 'mascot', 'founded', 'wins', 'losses', 'win_percentage', 'revenue', 'color']}, 'draft' => {'only' => [PK_COLUMN.to_s, 'created_at', 'updated_at', 'date', 'round', 'pick', 'overall', 'college', 'notes']}, 'comments' => {'only' => [PK_COLUMN.to_s, 'content', 'created_at', 'updated_at']}, }, } end it 'exports to CSV with custom schema' do page.driver.post(export_path(model_name: 'player', schema: custom_schema, csv: true, all: true, csv_options: {generator: {col_sep: ','}})) csv = CSV.parse page.driver.response.body expect(csv[0]).not_to include('Created at') end it 'exports polymorphic fields the easy way for now' do visit export_path(model_name: 'comment') select "<comma> ','", from: 'csv_options_generator_col_sep' click_button 'Export to csv' csv = CSV.parse page.driver.response.body expect(csv[0]).to match_array ['Id', 'Commentable', 'Commentable type', 'Content', 'Created at', 'Updated at'] csv[1..].each do |line| expect(line[csv[0].index('Commentable')]).to eq(player.id.to_s) expect(line[csv[0].index('Commentable type')]).to eq(player.class.to_s) end end end context 'on cancel' do before do @player = FactoryBot.create :player visit export_path(model_name: 'player') end it 'does nothing', js: true do find_button('Cancel').trigger('click') is_expected.to have_text 'No actions were taken' end end describe 'bulk export' do it 'is supported' do visit index_path(model_name: 'player') click_link 'Export found Players' is_expected.to have_content('Select fields to export') end describe 'with model scope' do let!(:comments) { %w[something anything].map { |content| FactoryBot.create :comment_confirmed, content: content } } before do RailsAdmin.config do |config| config.model Comment::Confirmed do scope { Comment::Confirmed.unscoped } end end end it 'overrides default_scope' do page.driver.post(export_path(model_name: 'comment~confirmed', schema: {only: ['content']}, csv: true, all: true, csv_options: {generator: {col_sep: ','}}, bulk_ids: comments.map(&:id))) csv = CSV.parse page.driver.response.body expect(csv.flatten).to match_array %w[Content something anything] end end end context 'with composite primary keys', composite_primary_keys: true do let!(:fanship) { FactoryBot.create(:fanship) } it 'exports to CSV' do visit export_path(model_name: 'fanship') click_button 'Export to csv' is_expected.to have_content fanship.fan.name is_expected.to have_content fanship.team.name end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/bulk_delete_spec.rb
spec/integration/actions/bulk_delete_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'BulkDelete action', type: :request do subject { page } describe 'confirmation page' do before do @players = FactoryBot.create_list(:player, 2) end it 'shows names of to-be-deleted players' do post(bulk_action_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: @players.collect(&:id))) @players.each { |player| expect(response.body).to include(player.name) } end it 'redirects to list when all of the records is already deleted' do expect(Player.count).to eq @players.length player_ids = [@players.first.id] @players.first.destroy # delete selected object before send request to show bulk_delete confirmation. post(bulk_action_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: player_ids)) expect(response.response_code).to eq 302 index_url = response.headers['Location'] expect(URI.parse(index_url).path).to eq(index_path(model_name: 'player')) visit index_url is_expected.to have_no_content(@players.first.name) is_expected.to have_content(@players.last.name) end it 'returns error message for DELETE request if the records are already deleted' do expect(Player.count).to eq @players.length player_ids = [@players.first.id] @players.first.destroy # delete selected object before send request to delete it. delete(bulk_delete_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: player_ids)) expect(response.response_code).to eq 302 expect(flash[:error]).to match(/0 players failed to be deleted/i) end it 'returns error message for DELETE request without bulk_ids' do expect(Player.count).to eq @players.length delete(bulk_delete_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: '')) expect(response.response_code).to eq 302 expect(flash[:error]).to match(/0 players failed to be deleted/i) end end context 'on destroy' do before do @players = Array.new(3) { FactoryBot.create(:player) } @delete_ids = @players[0..1].collect(&:id) # NOTE: This uses an internal, unsupported capybara API which could break at any moment. We # should refactor this test so that it either A) uses capybara's supported API (only GET # requests via visit) or B) just uses Rack::Test (and doesn't use capybara for browser # interaction like click_button). page.driver.browser.reset_host! page.driver.browser.process :post, bulk_action_path(bulk_action: 'bulk_delete', model_name: 'player', bulk_ids: @delete_ids, '_method' => 'post') click_button "Yes, I'm sure" end it 'does not contain deleted records' do expect(RailsAdmin::AbstractModel.new('Player').all.pluck(:id)).to eq([@players[2].id]) expect(page).to have_selector('.alert-success', text: '2 Players successfully deleted') end end context 'on cancel' do before do @players = Array.new(3) { FactoryBot.create(:player) } @delete_ids = @players[0..1].collect(&:id) visit index_path(model_name: 'player') @delete_ids.each { |id| find(%(input[name="bulk_ids[]"][value="#{id}"])).click } click_link 'Selected items' click_link 'Delete selected Players' end it 'does not delete records', js: true do find_button('Cancel').trigger('click') is_expected.to have_text 'No actions were taken' expect(RailsAdmin::AbstractModel.new('Player').count).to eq(3) end end context 'with composite primary keys', composite_primary_keys: true do let!(:fanships) { FactoryBot.create_list(:fanship, 3) } it 'provides check boxes for bulk operation' do visit index_path(model_name: 'fanship') fanships.each { |fanship| is_expected.to have_css(%(input[name="bulk_ids[]"][value="#{fanship.id}"])) } end it 'deletes selected records' do delete(bulk_delete_path(bulk_action: 'bulk_delete', model_name: 'fanship', bulk_ids: fanships[0..1].map { |fanship| RailsAdmin::Support::CompositeKeysSerializer.serialize(fanship.id) })) expect(flash[:success]).to match(/2 Fanships successfully deleted/) expect(Fanship.all).to eq fanships[2..2] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/new_spec.rb
spec/integration/actions/new_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'New action', type: :request do subject { page } describe 'page' do before do visit new_path(model_name: 'player') end it 'shows "New Model"' do is_expected.to have_content('New Player') end it 'shows required fields as "Required"' do is_expected.to have_selector('div', text: /Name\s*Required/) is_expected.to have_selector('div', text: /Number\s*Required/) end it 'shows non-required fields as "Optional"' do is_expected.to have_selector('#player_position_field .form-text', text: 'Optional') is_expected.to have_selector('#player_born_on_field .form-text', text: 'Optional') is_expected.to have_selector('#player_notes_field .form-text', text: 'Optional') end # https://github.com/railsadminteam/rails_admin/issues/362 # test that no link uses the "wildcard route" with the main # controller and new method it "does not use the 'wildcard route'" do is_expected.to have_no_selector("a[href^='/rails_admin/main/new']") end end context 'with missing label' do before do FactoryBot.create :team, name: '' visit new_path(model_name: 'player') end end context 'with parameters for pre-population' do it 'populates form field when corresponding parameters are passed in' do visit new_path(model_name: 'player', player: {name: 'Sam'}) expect(page).to have_css('input[value=Sam]') end it 'prepropulates has_one relationships' do @draft = FactoryBot.create :draft @player = FactoryBot.create :player, name: 'has_one association prepopulated' visit new_path(model_name: 'player', player: {draft_id: @draft.id}) expect(page).to have_css("select#player_draft_id option[selected='selected'][value='#{@draft.id}']") end it 'prepropulates has_many relationships' do @player = FactoryBot.create :player, name: 'has_many association prepopulated' visit new_path(model_name: 'team', team: {player_ids: [@player.id]}) expect(page).to have_css("select#team_player_ids option[selected='selected'][value='#{@player.id}']") end end context 'with namespaced model' do it 'has correct input field names' do visit new_path(model_name: 'cms~basic_page') is_expected.to have_selector('label[for=cms_basic_page_title]') is_expected.to have_selector("input#cms_basic_page_title[name='cms_basic_page[title]']") is_expected.to have_selector('label[for=cms_basic_page_content]') is_expected.to have_selector("textarea#cms_basic_page_content[name='cms_basic_page[content]']") end context 'with parameters for pre-population' do it 'populates form field when corresponding parameters are passed in' do visit new_path(model_name: 'cms~basic_page', cms_basic_page: {title: 'Hello'}) expect(page).to have_css('input[value=Hello]') end end it 'creates object with correct attributes' do visit new_path(model_name: 'cms~basic_page') fill_in 'cms_basic_page[title]', with: 'Hello' fill_in 'cms_basic_page[content]', with: 'World' expect do click_button 'Save' # first(:button, "Save").click end.to change(Cms::BasicPage, :count).by(1) end end context 'on create' do before do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' click_button 'Save' @player = RailsAdmin::AbstractModel.new('Player').first end it 'creates an object with correct attributes' do expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end context 'on create and edit' do before do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' click_button 'Save and edit' @player = RailsAdmin::AbstractModel.new('Player').first end it 'creates an object with correct attributes' do expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end context 'on create and add another', js: true do before do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' find_button('Save and add another').trigger('click') end it 'creates an object with correct attributes' do is_expected.to have_text 'Player successfully created' expect(page.current_path).to eq('/admin/player/new') @player = RailsAdmin::AbstractModel.new('Player').first expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end context 'with uniqueness constraint violated', given: 'a player exists' do before do @team = FactoryBot.create :team @player = FactoryBot.create :player, team: @team post new_path(model_name: 'player', player: {name: @player.name, number: @player.number.to_s, position: @player.position, team_id: @team.id}) end it 'shows an error message' do expect(response.body).to include('There is already a player with that number on this team') end end context 'with invalid object' do before do post new_path(model_name: 'player', player: {id: 1}) end it 'shows an error message' do expect(response.body).to include('Player failed to be created') end end context 'with object with errors on base' do before do visit new_path(model_name: 'player') fill_in 'player[name]', with: 'Jackie Robinson on steroids' click_button 'Save and add another' end it 'shows error base error message in flash' do is_expected.to have_content('Player failed to be created') is_expected.to have_content('Player is cheating') end end context 'with a readonly object' do it 'shows non-editable form' do RailsAdmin.config do |config| config.model ReadOnlyComment do edit do field :content end end end visit new_path(model_name: 'read_only_comment') is_expected.not_to have_css('textarea[name="read_only_comment[content]"]') is_expected.to have_css('button[name="_save"]:disabled') end end context 'with composite primary keys', composite_primary_keys: true do let!(:fan) { FactoryBot.create(:fan) } let!(:team) { FactoryBot.create(:team) } it 'creates an object' do visit new_path(model_name: 'fanship') select(fan.name, from: 'Fan') select(team.name, from: 'Team') expect { click_button 'Save' }.to change { Fanship.count }.by(1) expect(Fanship.first.attributes.fetch_values('fan_id', 'team_id')).to eq [fan.id, team.id] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/delete_spec.rb
spec/integration/actions/delete_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Delete action', type: :request do subject { page } it 'shows "Delete model"' do @draft = FactoryBot.create :draft @player = @draft.player @comment = @player.comments.create visit delete_path(model_name: 'player', id: @player.id) is_expected.to have_content('delete this player') is_expected.to have_link(@player.name, href: "/admin/player/#{@player.id}") is_expected.to have_link("Draft ##{@draft.id}", href: "/admin/draft/#{@draft.id}") is_expected.to have_link("Comment ##{@comment.id}", href: "/admin/comment/#{@comment.id}") end context 'with missing object' do before do visit delete_path(model_name: 'player', id: 1) end it 'raises NotFound' do expect(page.driver.status_code).to eq(404) end end context 'with show action disabled' do before do RailsAdmin.config.actions do dashboard index delete end @draft = FactoryBot.create :draft @player = @draft.player @comment = @player.comments.create visit delete_path(model_name: 'player', id: @player.id) end it 'shows "Delete model"' do is_expected.to have_content('delete this player') is_expected.not_to have_selector("a[href=\"/admin/player/#{@player.id}\"]") is_expected.not_to have_selector("a[href=\"/admin/draft/#{@draft.id}\"]") is_expected.not_to have_selector("a[href=\"/admin/comment/#{@comment.id}\"]") end end context 'on deleting an object which has an associated item without id' do before do @player = FactoryBot.create :player allow_any_instance_of(Player).to receive(:draft).and_return(Draft.new) visit delete_path(model_name: 'player', id: @player.id) end it 'shows "Delete model"' do is_expected.not_to have_content('Routing Error') is_expected.to have_content('delete this player') is_expected.to have_link(@player.name, href: "/admin/player/#{@player.id}") end end context 'on deleting an object which has many associated item' do before do comments = FactoryBot.create_list :comment, 20 @player = FactoryBot.create :player, comments: comments visit delete_path(model_name: 'player', id: @player.id) end it 'shows only ten first plus x mores', skip_mongoid: true do is_expected.to have_selector('.comment', count: 10) is_expected.to have_content('Plus 10 more Comments') end end context 'on destroy' do before do @player = FactoryBot.create :player visit delete_path(model_name: 'player', id: @player.id) click_button "Yes, I'm sure" @player = RailsAdmin::AbstractModel.new('Player').first end it 'destroys an object' do expect(@player).to be_nil end it 'shows success message' do is_expected.to have_content('Player successfully deleted') end end context 'with destroy errors' do before do allow_any_instance_of(Player).to receive(:destroy_hook) { throw :abort } @player = FactoryBot.create :player visit delete_path(model_name: 'player', id: @player.id) click_button "Yes, I'm sure" end it 'does not destroy an object' do expect(@player.reload).to be end it 'shows error message' do is_expected.to have_content('Player failed to be deleted') end it 'returns status code 406' do expect(page.status_code).to eq(406) end end context 'on destroy error by dependent: :restrict_with_error' do let!(:player) { FactoryBot.create :player, team: FactoryBot.create(:restricted_team) } before do visit delete_path(model_name: 'restricted_team', id: player.team.id) click_button "Yes, I'm sure" is_expected.to have_content('Restricted team failed to be deleted') end it 'shows error message', active_record: true do is_expected.to have_content('Cannot delete record because dependent players exist') end it 'shows error message', mongoid: true do is_expected.to have_content('Players is not empty and prevents the document from being destroyed') end end context 'on cancel' do before do @player = FactoryBot.create :player visit delete_path(model_name: 'player', id: @player.id) end it 'does not destroy an object', js: true do find_button('Cancel').trigger('click') is_expected.to have_text 'No actions were taken' expect(RailsAdmin::AbstractModel.new('Player').first).to be end end context 'with missing object' do before do delete delete_path(model_name: 'player', id: 1) end it 'raises NotFound' do expect(response.code).to eq('404') end end context 'when navigated to delete from show page' do it 'redirects to the index instead of trying to show the deleted object' do @player = FactoryBot.create :player visit show_path(model_name: 'player', id: @player.id) click_link 'Delete' click_button "Yes, I'm sure" expect(URI.parse(page.current_url).path).to eq(index_path(model_name: 'player')) end it 'stays on the delete page' do allow_any_instance_of(Player).to receive(:destroy_hook) { throw :abort } @player = FactoryBot.create :player visit show_path(model_name: 'player', id: @player.id) click_link 'Delete' click_button "Yes, I'm sure" expect(URI.parse(page.current_url).path).to eq(delete_path(model_name: 'player', id: @player.id)) end end context 'with composite primary keys', composite_primary_keys: true do let(:fanship) { FactoryBot.create(:fanship) } it 'deletes the object' do visit delete_path(model_name: 'fanship', id: fanship.id) click_button "Yes, I'm sure" is_expected.to have_content('Fanship successfully deleted') expect(Fanship.all).to be_empty end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/history_show_spec.rb
spec/integration/actions/history_show_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'HistoryShow action', type: :request, active_record: true do let(:user) { FactoryBot.create :user } let(:paper_trail_test) { FactoryBot.create :paper_trail_test } before(:each) do RailsAdmin.config do |config| config.audit_with :paper_trail, 'User', 'PaperTrail::Version' end PaperTrail::Version.delete_all with_versioning do PaperTrail.request.whodunnit = user.id 30.times do |i| paper_trail_test.update!(name: "updated name #{i}") end end end it 'shows the history' do visit history_show_path(model_name: 'paper_trail_test', id: paper_trail_test.id) expect(all('table#history tbody tr').count).to eq(20) end it 'supports pagination' do visit history_show_path(model_name: 'paper_trail_test', id: paper_trail_test.id, page: 2) expect(all('table#history tbody tr').count).to eq(11) end context "when Kaminari's custom param_name is set" do before { Kaminari.config.param_name = :pagina } after { Kaminari.config.param_name = :page } it 'picks the page value from params' do visit history_show_path(model_name: 'paper_trail_test', id: paper_trail_test.id, pagina: 2) expect(all('table#history tbody tr').count).to eq(11) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/history_index_spec.rb
spec/integration/actions/history_index_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'HistoryIndex action', type: :request, active_record: true do subject { page } let(:user) { FactoryBot.create :user } let(:paper_trail_test) { FactoryBot.create :paper_trail_test } before(:each) do RailsAdmin.config do |config| config.audit_with :paper_trail, 'User', 'PaperTrail::Version' end PaperTrail::Version.delete_all with_versioning do PaperTrail.request.whodunnit = user.id 30.times do |i| paper_trail_test.update!(name: "updated name #{i}") end end end it 'shows the history' do visit history_index_path(model_name: 'paper_trail_test') is_expected.to have_css(%([href="/admin/paper_trail_test/#{paper_trail_test.id}"]), count: 20) end it 'supports pagination' do visit history_index_path(model_name: 'paper_trail_test', page: 2) is_expected.to have_css(%([href="/admin/paper_trail_test/#{paper_trail_test.id}"]), count: 11) end it 'supports sorting', js: true do visit history_index_path(model_name: 'paper_trail_test') find('th.header', text: 'Item').click is_expected.to have_css('th.item.headerSortDown') end context "when Kaminari's custom param_name is set" do before { Kaminari.config.param_name = :pagina } after { Kaminari.config.param_name = :page } it 'picks the page value from params' do visit history_index_path(model_name: 'paper_trail_test', pagina: 2) is_expected.to have_css(%([href="/admin/paper_trail_test/#{paper_trail_test.id}"]), count: 11) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/dashboard_spec.rb
spec/integration/actions/dashboard_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Dashboard action', type: :request do subject { page } it 'shows statistics by default' do allow(RailsAdmin.config(Player).abstract_model).to receive(:count).and_return(0) expect(RailsAdmin.config(Player).abstract_model).to receive(:count) visit dashboard_path end it 'does not show statistics if turned off' do RailsAdmin.config do |c| c.included_models = [Player] c.actions do dashboard do statistics false end index # mandatory end end expect(RailsAdmin.config(Player).abstract_model).not_to receive(:count) visit dashboard_path end it 'does not show history if turned off', active_record: true do RailsAdmin.config do |c| c.audit_with :paper_trail, 'User', 'PaperTrail::Version' c.included_models = [PaperTrailTest] c.actions do dashboard do history false end index # mandatory new history_index end end with_versioning do visit new_path(model_name: 'paper_trail_test') fill_in 'paper_trail_test[name]', with: 'Jackie Robinson' click_button 'Save' end visit dashboard_path is_expected.not_to have_content 'Jackie Robinson' end it 'counts are different for same-named models in different modules' do allow(RailsAdmin.config(User::Confirmed).abstract_model).to receive(:count).and_return(10) allow(RailsAdmin.config(Comment::Confirmed).abstract_model).to receive(:count).and_return(0) visit dashboard_path expect(find('tr.user_confirmed_links .progress').text).to eq '10' expect(find('tr.comment_confirmed_links .progress').text).to eq '0' end it 'most recent change dates are different for same-named models in different modules' do user_create = 10.days.ago comment_create = 20.days.ago FactoryBot.create(:user_confirmed, created_at: user_create) FactoryBot.create(:comment_confirmed, created_at: comment_create) visit dashboard_path expect(find('tr.user_confirmed_links')).to have_content '10 days ago' expect(find('tr.comment_confirmed_links')).to have_content '20 days ago' end describe 'I18n' do around do |example| I18n.config.available_locales = I18n.config.available_locales + [:xx] I18n.backend.class.send(:include, I18n::Backend::Pluralization) I18n.backend.store_translations :xx, admin: { misc: { ago: 'back', }, }, datetime: { distance_in_words: { x_days: { one: '1 day', }, }, } I18n.locale = :xx example.run I18n.locale = :en I18n.config.available_locales = I18n.config.available_locales - [:xx] end it "fallbacks to 'ago' when 'time_ago' is not available" do FactoryBot.create(:player, created_at: 1.day.ago) visit dashboard_path expect(page).to have_content '1 day back' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/base_spec.rb
spec/integration/actions/base_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Base action', type: :request do subject { page } describe '#enabled?' do it 'prevents the access to unauthorized actions' do RailsAdmin.config do |config| config.actions do index do except %w[FieldTest] end end end expect { visit index_path(model_name: 'field_test') }.to raise_error 'RailsAdmin::ActionNotAllowed' end describe 'in form action' do before do RailsAdmin.config do |config| config.actions do index new edit do except %w[Player Team] end end end end describe 'for filterling-select widget' do it 'hides modal links to disabled actions' do visit new_path(model_name: 'player') expect(page).to have_link 'Add a new Team' expect(page).not_to have_link 'Edit this Team' end end describe 'for filterling-multiselect widget' do it 'hides edit link to another model' do visit new_path(model_name: 'team') expect(page).to have_link 'Add a new Player' expect(page).not_to have_link 'Edit this Player' end end end context 'when used with #visible?' do let!(:player) { FactoryBot.create(:player) } before do RailsAdmin.config do |config| config.actions do index show edit do enabled false visible true end end end end it 'allows disabled links to be shown' do visit index_path(model_name: 'player') is_expected.to have_css('.edit_member_link.disabled span', text: /Edit/, visible: false) visit show_path(model_name: 'player', id: player.id) is_expected.to have_css('.edit_member_link.disabled a[href*="void(0)"]') end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/edit_spec.rb
spec/integration/actions/edit_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Edit action', type: :request do subject { page } describe 'page' do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) end it 'shows "Edit model"' do is_expected.to have_content('Edit Player') end it 'shows required fields as "Required"' do is_expected.to have_selector('div', text: /Name\s*Required/) is_expected.to have_selector('div', text: /Number\s*Required/) end it 'shows non-required fields as "Optional"' do expect(find('#player_position_field .form-text')).to have_content('Optional') expect(find('#player_born_on_field .form-text')).to have_content('Optional') expect(find('#player_notes_field .form-text')).to have_content('Optional') end it 'checks required fields to have required attribute set' do expect(find_field('player_name')[:required]).to be_present expect(find_field('player_number')[:required]).to be_present end it 'checks optional fields to not have required attribute set' do expect(find_field('player_position')[:required]).to be_blank end end describe 'css hooks' do it 'is present' do visit new_path(model_name: 'team') is_expected.to have_selector('#team_division_id_field.belongs_to_association_type.division_field') end end describe 'field grouping' do it 'is hideable' do RailsAdmin.config Team do edit do group :default do label 'Hidden group' hide end end end visit new_path(model_name: 'team') # Should not have the group header is_expected.to have_no_selector('legend', text: 'Hidden Group') # Should not have any of the group's fields either is_expected.to have_no_selector('select#team_division') is_expected.to have_no_selector('input#team_name') is_expected.to have_no_selector('input#team_logo_url') is_expected.to have_no_selector('input#team_manager') is_expected.to have_no_selector('input#team_ballpark') is_expected.to have_no_selector('input#team_mascot') is_expected.to have_no_selector('input#team_founded') is_expected.to have_no_selector('input#team_wins') is_expected.to have_no_selector('input#team_losses') is_expected.to have_no_selector('input#team_win_percentage') is_expected.to have_no_selector('input#team_revenue') end it 'hides association groupings' do RailsAdmin.config Team do edit do group :players do label 'Players' field :players hide end end end visit new_path(model_name: 'team') # Should not have the group header is_expected.to have_no_selector('legend', text: 'Players') # Should not have any of the group's fields either is_expected.to have_no_selector('select#team_player_ids') end it 'is renameable' do RailsAdmin.config Team do edit do group :default do label 'Renamed group' end end end visit new_path(model_name: 'team') # NOTE: capybara 2.0 is exceedingly reluctant to reveal the text of invisible elements. This was # the least terrible option I was able to find. It would probably be better to refactor the test # so the label we're looking for is displayed. expect(find('legend', visible: false).native.text).to include('Renamed group') end describe 'help' do before do class HelpTest < Tableless column :name, 'varchar(50)' column :division, :varchar end RailsAdmin.config.included_models = [HelpTest, Team] end after(:each) do # restore validation setting HelpTest._validators[:name] = [] HelpTest.reset_callbacks(:validate) end context 'using mongoid', skip_active_record: true do it 'uses the db column size for the maximum length' do visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length up to 255.') end it 'returns nil for the maximum length' do visit new_path(model_name: 'team') expect(find('#team_custom_field_field .form-text')).not_to have_content('Length') end end context 'using active_record', skip_mongoid: true do it 'uses the db column size for the maximum length' do visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length up to 50.') end it 'uses the :minimum setting from the validation' do HelpTest.class_eval do validates_length_of :name, minimum: 1 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length of 1-50.') end it 'uses the minimum of db column size or :maximum setting from the validation' do HelpTest.class_eval do validates_length_of :name, maximum: 51 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length up to 50.') end end it 'shows help section if present' do RailsAdmin.config HelpTest do edit do group :default do help 'help paragraph to display' end end end visit new_path(model_name: 'help_test') is_expected.to have_selector('fieldset>p', text: 'help paragraph to display') end it 'does not show help if not present' do RailsAdmin.config HelpTest do edit do group :default do label 'no help' end end end visit new_path(model_name: 'help_test') is_expected.not_to have_selector('fieldset>p') end it 'is able to display multiple help if there are multiple sections' do RailsAdmin.config HelpTest do edit do group :default do field :name help 'help for default' end group :other_section do label 'Other Section' field :division help 'help for other section' end end end visit new_path(model_name: 'help_test') is_expected.to have_selector('fieldset>p', text: 'help for default') is_expected.to have_selector('fieldset>p', text: 'help for other section') is_expected.to have_selector('fieldset>p', count: 2) end it 'uses the :is setting from the validation' do HelpTest.class_eval do validates_length_of :name, is: 3 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length of 3.') end it 'uses the :maximum setting from the validation' do HelpTest.class_eval do validates_length_of :name, maximum: 49 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length up to 49.') end it 'uses the :minimum and :maximum from the validation' do HelpTest.class_eval do validates_length_of :name, minimum: 1, maximum: 49 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length of 1-49.') end it 'uses the range from the validation' do HelpTest.class_eval do validates_length_of :name, in: 1..49 end visit new_path(model_name: 'help_test') expect(find('#help_test_name_field .form-text')).to have_content('Length of 1-49.') end it 'does not show help for hidden fields' do RailsAdmin.config HelpTest do edit do field :name, :hidden end end visit new_path(model_name: 'help_test') expect(page).not_to have_css('.form-text') end end it 'has accessor for its fields' do RailsAdmin.config Team do edit do group :default do field :name field :logo_url end group :belongs_to_associations do label "Belong's to associations" field :division end group :basic_info do field :manager end end end visit new_path(model_name: 'team') is_expected.to have_selector('legend', text: 'Basic info', visible: false) is_expected.to have_selector('legend', text: 'Basic info', visible: true) is_expected.to have_selector('legend', text: "Belong's to associations") is_expected.to have_selector('label', text: 'Name') is_expected.to have_selector('label', text: 'Logo url') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('.control-group', count: 4) end it 'has accessor for its fields by type' do RailsAdmin.config Team do edit do group :default do field :name field :logo_url end group :other do field :division_id field :manager field :ballpark fields_of_type :string do label { "#{label} (STRING)" } end end end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Name') is_expected.to have_selector('label', text: 'Logo url') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('label', text: 'Manager (STRING)') is_expected.to have_selector('label', text: 'Ballpark (STRING)') end end describe 'fields' do it 'shows all by default' do visit new_path(model_name: 'team') is_expected.to have_selector('select#team_division_id') is_expected.to have_selector('input#team_name') is_expected.to have_selector('input#team_logo_url') is_expected.to have_selector('input#team_manager') is_expected.to have_selector('input#team_ballpark') is_expected.to have_selector('input#team_mascot') is_expected.to have_selector('input#team_founded') is_expected.to have_selector('input#team_wins') is_expected.to have_selector('input#team_losses') is_expected.to have_selector('input#team_win_percentage') is_expected.to have_selector('input#team_revenue') is_expected.to have_selector('select#team_player_ids') is_expected.to have_selector('select#team_fan_ids') end it 'appears in order defined' do RailsAdmin.config Team do edit do field :manager field :division field :name end end visit new_path(model_name: 'team') is_expected.to have_selector(:xpath, "//*[contains(@class, 'field')][1]//*[@id='team_manager']") is_expected.to have_selector(:xpath, "//*[contains(@class, 'field')][2]//*[@id='team_division_id']") is_expected.to have_selector(:xpath, "//*[contains(@class, 'field')][3]//*[@id='team_name']") end it 'only shows the defined fields if some fields are defined' do RailsAdmin.config Team do edit do field :division field :name end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('label', text: 'Name') is_expected.to have_selector('.control-group', count: 2) end describe 'I18n awarly' do after :each do I18n.locale = :en end it 'delegates the label option to the ActiveModel API and memoizes it' do RailsAdmin.config Team do edit do field :manager field :fans end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Team Manager') is_expected.to have_selector('label', text: 'Some Fans') I18n.locale = :fr visit new_path(model_name: 'team') is_expected.to have_selector('label', text: "Manager de l'équipe") is_expected.to have_selector('label', text: 'Quelques fans') end end it 'is renameable' do RailsAdmin.config Team do edit do field :manager do label 'Renamed field' end field :division field :name end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Renamed field') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('label', text: 'Name') end it 'is renameable by type' do RailsAdmin.config Team do edit do fields_of_type :string do label { "#{label} (STRING)" } end end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('label', text: 'Name (STRING)') is_expected.to have_selector('label', text: 'Logo url (STRING)') is_expected.to have_selector('label', text: 'Manager (STRING)') is_expected.to have_selector('label', text: 'Ballpark (STRING)') is_expected.to have_selector('label', text: 'Mascot (STRING)') is_expected.to have_selector('label', text: 'Founded') is_expected.to have_selector('label', text: 'Wins') is_expected.to have_selector('label', text: 'Losses') is_expected.to have_selector('label', text: 'Win percentage') is_expected.to have_selector('label', text: 'Revenue') is_expected.to have_selector('label', text: 'Players') is_expected.to have_selector('label', text: 'Fans') end it 'is globally renameable by type' do RailsAdmin.config Team do edit do fields_of_type :string do label { "#{label} (STRING)" } end end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Division') is_expected.to have_selector('label', text: 'Name (STRING)') is_expected.to have_selector('label', text: 'Logo url (STRING)') is_expected.to have_selector('label', text: 'Manager (STRING)') is_expected.to have_selector('label', text: 'Ballpark (STRING)') is_expected.to have_selector('label', text: 'Mascot (STRING)') is_expected.to have_selector('label', text: 'Founded') is_expected.to have_selector('label', text: 'Wins') is_expected.to have_selector('label', text: 'Losses') is_expected.to have_selector('label', text: 'Win percentage') is_expected.to have_selector('label', text: 'Revenue') is_expected.to have_selector('label', text: 'Players') is_expected.to have_selector('label', text: 'Fans') end it 'is flaggable as read only and be configurable with formatted_value' do RailsAdmin.config Team do edit do field :name do read_only true formatted_value do "I'm outputted in the form" end end end end visit new_path(model_name: 'team') is_expected.to have_content("I'm outputted in the form") end it 'is hideable' do RailsAdmin.config Team do edit do field :manager do hide end field :division field :name end end visit new_path(model_name: 'team') is_expected.to have_no_selector('#team_manager') is_expected.to have_selector('#team_division_id') is_expected.to have_selector('#team_name') end it 'is hideable by type' do RailsAdmin.config Team do edit do fields_of_type :string do hide end end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Division') is_expected.to have_no_selector('label', text: 'Name') is_expected.to have_no_selector('label', text: 'Logo url') is_expected.to have_no_selector('label', text: 'Manager') is_expected.to have_no_selector('label', text: 'Ballpark') is_expected.to have_no_selector('label', text: 'Mascot') is_expected.to have_selector('label', text: 'Founded') is_expected.to have_selector('label', text: 'Wins') is_expected.to have_selector('label', text: 'Losses') is_expected.to have_selector('label', text: 'Win percentage') is_expected.to have_selector('label', text: 'Revenue') is_expected.to have_selector('label', text: 'Players') is_expected.to have_selector('label', text: 'Fans') end it 'is globally hideable by type' do RailsAdmin.config Team do edit do fields_of_type :string do hide end end end visit new_path(model_name: 'team') is_expected.to have_selector('label', text: 'Division') is_expected.to have_no_selector('label', text: 'Name') is_expected.to have_no_selector('label', text: 'Logo url') is_expected.to have_no_selector('label', text: 'Manager') is_expected.to have_no_selector('label', text: 'Ballpark') is_expected.to have_no_selector('label', text: 'Mascot') is_expected.to have_selector('label', text: 'Founded') is_expected.to have_selector('label', text: 'Wins') is_expected.to have_selector('label', text: 'Losses') is_expected.to have_selector('label', text: 'Win percentage') is_expected.to have_selector('label', text: 'Revenue') is_expected.to have_selector('label', text: 'Players') is_expected.to have_selector('label', text: 'Fans') end it 'has option to customize the help text' do RailsAdmin.config Team do edit do field :manager do help "#{help} Additional help text for manager field." end field :division field :name end end visit new_path(model_name: 'team') expect(find('#team_manager_field .form-text')).to have_content('Required. Length up to 100. Additional help text for manager field.') expect(find('#team_division_id_field .form-text')).to have_content('Required') expect(find('#team_name_field .form-text')).not_to have_content('Additional help text') end it 'has option to override required status' do RailsAdmin.config Team do edit do field :manager do optional true end field :division do optional true end field :name do required true end end end visit new_path(model_name: 'team') expect(find('#team_manager_field .form-text')).to have_content('Optional') expect(find('#team_division_id_field .form-text')).to have_content('Optional') expect(find('#team_name_field .form-text')).to have_content(I18n.translate('admin.help.team.name')) end describe 'inline_add' do it 'can hide the add button on an associated field' do RailsAdmin.config Player do edit do field :team do inline_add false end field :draft do inline_add false end field :comments do inline_add false end end end visit new_path(model_name: 'player') is_expected.to have_no_selector('a', text: 'Add a new Team') is_expected.to have_no_selector('a', text: 'Add a new Draft') is_expected.to have_no_selector('a', text: 'Add a new Comment') end it 'can show the add button on an associated field' do RailsAdmin.config Player do edit do field :team do inline_add true end field :draft do inline_add true end field :comments do inline_add true end end end visit new_path(model_name: 'player') is_expected.to have_selector('a', text: 'Add a new Team') is_expected.to have_selector('a', text: 'Add a new Draft') is_expected.to have_selector('a', text: 'Add a new Comment') end context 'when the associated model is invisible' do before do RailsAdmin.config do |config| [Team, Draft, Comment].each do |model| config.model model do visible false end end end end it 'does not prevent showing the add button' do visit new_path(model_name: 'player') is_expected.to have_selector('a', text: 'Add a new Team') is_expected.to have_selector('a', text: 'Add a new Draft') is_expected.to have_selector('a', text: 'Add a new Comment') end end end describe 'inline_edit' do it 'can hide the edit button on an associated field' do RailsAdmin.config Player do edit do field :team do inline_edit false end field :draft do inline_edit false end end end visit new_path(model_name: 'player') is_expected.to have_no_selector('a', text: 'Edit this Team') is_expected.to have_no_selector('a', text: 'Edit this Draft') end it 'can show the edit button on an associated field' do RailsAdmin.config Player do edit do field :team do inline_edit true end field :draft do inline_edit true end end end visit new_path(model_name: 'player') is_expected.to have_selector('a', text: 'Edit this Team') is_expected.to have_selector('a', text: 'Edit this Draft') end context 'when the associated model is invisible' do before do RailsAdmin.config do |config| [Team, Draft].each do |model| config.model model do visible false end end end end it 'does not prevent showing the edit button' do visit new_path(model_name: 'player') is_expected.to have_selector('a', text: 'Edit this Team') is_expected.to have_selector('a', text: 'Edit this Draft') end end end end context 'with missing object' do before do visit edit_path(model_name: 'player', id: 1) end it 'raises NotFound' do expect(page.driver.status_code).to eq(404) end end context 'with a readonly object' do let(:comment) { FactoryBot.create :comment, (CI_ORM == :mongoid ? {_type: 'ReadOnlyComment'} : {}) } it 'raises ActionNotAllowed' do expect { visit edit_path(model_name: 'read_only_comment', id: comment.id) }.to raise_error 'RailsAdmin::ActionNotAllowed' end end context 'with missing label', given: ['a player exists', 'three teams with no name exist'] do before do @player = FactoryBot.create :player @teams = Array.new(3) { FactoryBot.create :team, name: '' } visit edit_path(model_name: 'player', id: @player.id) end end context 'with overridden to_param' do before do @ball = FactoryBot.create :ball visit edit_path(model_name: 'ball', id: @ball.id) end it 'displays a link to the delete page' do is_expected.to have_selector "a[href$='/admin/ball/#{@ball.id}/delete']" end end context 'on cancel' do before do @player = FactoryBot.create :player visit '/admin/player' click_link 'Edit' end it 'sends back to previous URL', js: true do find_button('Cancel').trigger('click') is_expected.to have_text 'No actions were taken' expect(page.current_path).to eq('/admin/player') end it 'allows submit even if client-side validation is not satisfied', js: true do fill_in 'player[name]', with: '' find_button('Cancel').trigger('click') is_expected.to have_text 'No actions were taken' end end context 'with errors' do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) end it 'returns to edit page' do fill_in 'player[name]', with: '' click_button 'Save' # first(:button, "Save").click expect(page.driver.status_code).to eq(406) is_expected.to have_selector "form[action='#{edit_path(model_name: 'player', id: @player.id)}']" end end describe 'add another' do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' click_button 'Save' # first(:button, "Save").click @player = RailsAdmin::AbstractModel.new('Player').first end it 'updates an object with correct attributes' do expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end describe 'update and edit', js: true do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: '42' fill_in 'player[position]', with: 'Second baseman' find_button('Save and edit').trigger('click') end it 'updates an object with correct attributes' do is_expected.to have_text 'Player successfully updated' expect(page.current_path).to eq("/admin/player/#{@player.id}/edit") @player.reload expect(@player.name).to eq('Jackie Robinson') expect(@player.number).to eq(42) expect(@player.position).to eq('Second baseman') end end context 'with a submit button with custom value', js: true do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) execute_script %{$('.form-actions [name="_save"]').attr('name', 'player[name]').attr('value', 'Jackie Robinson')} find_button('Save').trigger('click') is_expected.to have_text 'Player successfully updated' end it 'submits the value' do @player.reload expect(@player.name).to eq('Jackie Robinson') end end context 'with missing object' do before do put edit_path(model_name: 'player', id: 1), params: {player: {name: 'Jackie Robinson', number: 42, position: 'Second baseman'}} end it 'raises NotFound' do expect(response.code).to eq('404') end end context 'with invalid object' do before do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) fill_in 'player[name]', with: 'Jackie Robinson' fill_in 'player[number]', with: 'a' fill_in 'player[position]', with: 'Second baseman' click_button 'Save' # first(:button, "Save").click @player.reload end it 'shows an error message' do expect(Capybara.string(body)).to have_content('Player failed to be updated') end end context 'with overridden to_param' do before do @ball = FactoryBot.create :ball visit edit_path(model_name: 'ball', id: @ball.id) fill_in 'ball[color]', with: 'gray' click_button 'Save and edit' @ball.reload end it 'updates an object with correct attributes' do expect(@ball.color).to eq('gray') end end context 'on update of STI subclass on superclass view' do before do @hardball = FactoryBot.create :hardball visit edit_path(model_name: 'ball', id: @hardball.id) fill_in 'ball[color]', with: 'cyan' click_button 'Save and edit' @hardball.reload end it 'updates an object with correct attributes' do expect(@hardball.color).to eq('cyan') end end context "with a field with 'format' as a name (conflicts with Kernel#format)" do it 'is updatable without any error' do RailsAdmin.config FieldTest do edit do field :format end end visit new_path(model_name: 'field_test') fill_in 'field_test[format]', with: 'test for format' click_button 'Save' # first(:button, "Save").click @record = RailsAdmin::AbstractModel.new('FieldTest').first expect(@record.format).to eq('test for format') end end context "with a field with 'open' as a name" do it 'is updatable without any error' do RailsAdmin.config FieldTest do edit do field :open do nullable false end end end record = FieldTest.create visit edit_path(model_name: 'field_test', id: record.id) expect do check 'field_test[open]' click_button 'Save' end.to change { record.reload.open }.from(nil).to(true) end end context 'with composite primary keys', composite_primary_keys: true do let(:fanship) { FactoryBot.create(:fanship) } it 'edits the object' do visit edit_path(model_name: 'fanship', id: fanship.id) fill_in 'Since', with: '2000-01-23' click_button 'Save' expect { fanship.reload }.to change { fanship.since }.from(nil).to(Date.new(2000, 1, 23)) end context 'using custom serializer' do before do RailsAdmin.config.composite_keys_serializer = Class.new do def self.serialize(keys) keys.join(',') end def self.deserialize(string) string.split(',') end end end it 'edits the object' do visit edit_path(model_name: 'fanship', id: "#{fanship.fan_id},#{fanship.team_id}") fill_in 'Since', with: '2000-01-23' click_button 'Save' expect { fanship.reload }.to change { fanship.since }.from(nil).to(Date.new(2000, 1, 23)) end end context 'receiving invalid id' do it 'returns 404' do visit edit_path(model_name: 'fanship', id: '11') expect(page.driver.status_code).to eq(404) is_expected.to have_content("Fanship with id '11' could not be found") end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/show_in_app_spec.rb
spec/integration/actions/show_in_app_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'ShowInApp action', type: :request do subject { page } describe 'link' do let!(:player) { FactoryBot.create :player } it 'has the data-turbo: false attribute' do visit index_path(model_name: 'player') is_expected.to have_selector(%(li[title="Show in app"] a[data-turbo="false"])) click_link 'Show' is_expected.to have_selector(%(a[data-turbo="false"]), text: 'Show in app') end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/actions/index_spec.rb
spec/integration/actions/index_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Index action', type: :request do subject { page } describe 'page' do it 'shows "List of Models", should show filters and should show column headers' do RailsAdmin.config.default_items_per_page = 1 2.times { FactoryBot.create :player } # two pages of players visit index_path(model_name: 'player') is_expected.to have_content('List of Players') is_expected.to have_content('Created at') is_expected.to have_content('Updated at') # it "shows the show, edit and delete links" do is_expected.to have_selector("li[title='Show'] a") is_expected.to have_selector("li[title='Edit'] a") is_expected.to have_selector("li[title='Delete'] a") # it "has the search box with some prompt text" do is_expected.to have_selector("input[placeholder='Filter']") # https://github.com/railsadminteam/rails_admin/issues/362 # test that no link uses the "wildcard route" with the main # controller and list method # it "does not use the 'wildcard route'" do is_expected.to have_selector("a[href*='all=true']") # make sure we're fully testing pagination is_expected.to have_no_selector("a[href^='/rails_admin/main/list']") end end describe 'css hooks' do it 'is present' do RailsAdmin.config Team do list do field :name end end FactoryBot.create :team visit index_path(model_name: 'team') is_expected.to have_selector('th.header.string_type.name_field') is_expected.to have_selector('td.string_type.name_field') end end describe 'with querying and filtering' do before do @teams = Array.new(2) do FactoryBot.create(:team) end @players = [ FactoryBot.create(:player, retired: true, injured: true, team: @teams[0]), FactoryBot.create(:player, retired: true, injured: false, team: @teams[0]), FactoryBot.create(:player, retired: false, injured: true, team: @teams[1]), FactoryBot.create(:player, retired: false, injured: false, team: @teams[1]), ] @comment = FactoryBot.create(:comment, commentable: @players[2]) end it 'allows to query on any attribute' do RailsAdmin.config Player do list do field :name field :team field :injured field :retired end end visit index_path(model_name: 'player', query: @players[0].name) is_expected.to have_content(@players[0].name) (1..3).each do |i| is_expected.to have_no_content(@players[i].name) end end it 'allows to clear the search query box', js: true do visit index_path(model_name: 'player', query: @players[0].name) is_expected.not_to have_content(@players[1].name) find_button('Reset filters').click is_expected.to have_content(@players[1].name) end it 'allows to filter on one attribute' do RailsAdmin.config Player do list do field :name field :team field :injured field :retired end end visit index_path(model_name: 'player', f: {injured: {'1' => {v: 'true'}}}) is_expected.to have_content(@players[0].name) is_expected.to have_no_content(@players[1].name) is_expected.to have_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to combine filters on two different attributes' do RailsAdmin.config Player do list do field :name field :team field :injured field :retired end end visit index_path(model_name: 'player', f: {retired: {'1' => {v: 'true'}}, injured: {'1' => {v: 'true'}}}) is_expected.to have_content(@players[0].name) (1..3).each do |i| is_expected.to have_no_content(@players[i].name) end end it 'allows to filter on belongs_to relationships' do RailsAdmin.config Player do list do field :name field :team field :injured field :retired end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams[0].name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to filter on has_one relationships' do @draft = FactoryBot.create(:draft, player: @players[1], college: 'University of Alabama') RailsAdmin.config Player do list do field :name field :draft do searchable :college end end end visit index_path(model_name: 'player', f: {draft: {'1' => {v: 'Alabama'}}}) is_expected.to have_content(@players[1].name) is_expected.to have_css('tbody .name_field', count: 1) end it 'allows to disable search on attributes' do RailsAdmin.config Player do list do field :position field :name do searchable false end end end visit index_path(model_name: 'player', query: @players[0].name) is_expected.to have_no_content(@players[0].name) end it 'allows to search a belongs_to attribute over the base table' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable Player => :team_id end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.id}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a belongs_to attribute over the target table' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable Team => :name end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a belongs_to attribute over the target table with a table name specified as a hash' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable teams: :name end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a belongs_to attribute over the target table with a table name specified as a string' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable 'teams.name' end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a belongs_to attribute over the label method by default' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a belongs_to attribute over the target table when an attribute is specified' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable :name end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search over more than one attribute' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :team do searchable [:name, {Player => :team_id}] end end end visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}, '2' => {v: @teams.first.id, o: 'is'}}}) is_expected.to have_content(@players[0].name) is_expected.to have_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) # same with a different id visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}, '2' => {v: @teams.last.id, o: 'is'}}}) is_expected.to have_no_content(@players[0].name) is_expected.to have_no_content(@players[1].name) is_expected.to have_no_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'allows to search a has_many attribute over the target table' do RailsAdmin.config Player do list do field PK_COLUMN field :name field :comments do searchable :content end end end visit index_path(model_name: 'player', f: {comments: {'1' => {v: @comment.content}}}) is_expected.to have_no_content(@players[0].name) is_expected.to have_no_content(@players[1].name) is_expected.to have_content(@players[2].name) is_expected.to have_no_content(@players[3].name) end it 'displays base filters when no filters are present in the params' do RailsAdmin.config Player do list { filters(%i[name team]) } field :name do default_filter_operator 'is' end field :team do filterable true end end visit index_path(model_name: 'player') expect(JSON.parse(find('#filters_box')['data-options']).map(&:symbolize_keys)).to match_array [ { index: 1, label: 'Name', name: 'name', type: 'string', value: '', operator: 'is', operators: %w[_discard like not_like is starts_with ends_with], }, { index: 2, label: 'Team', name: 'team', type: 'belongs_to_association', value: '', operator: nil, operators: %w[_discard like not_like is starts_with ends_with _separator _present _blank], }, ] end it 'shows the help text below the search box' do RailsAdmin.config Player do list do search_help 'Use this box to search!' end end visit index_path(model_name: 'player') is_expected.to have_css('.form-text', text: /Use this box/) end end describe 'fields' do before do if defined?(ActiveRecord) && ActiveRecord.gem_version >= Gem::Version.new('7.1') || defined?(CompositePrimaryKeys) RailsAdmin.config Fan do configure(:fanships) { hide } configure(:fanship) { hide } end end end it 'shows all by default' do visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Created at', 'Updated at', 'Their Name', 'Teams'] end it 'hides some fields on demand with a block' do RailsAdmin.config Fan do list do exclude_fields_if do type == :datetime end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Their Name', 'Teams'] end it 'hides some fields on demand with fields list' do RailsAdmin.config Fan do list do exclude_fields :created_at, :updated_at end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Their Name', 'Teams'] end it 'adds some fields on demand with a block' do RailsAdmin.config Fan do list do include_fields_if do type != :datetime end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Their Name', 'Teams'] end it 'shows some fields on demand with fields list, respect ordering and configure them' do RailsAdmin.config Fan do list do fields :name, PK_COLUMN do label do "Modified #{label}" end end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Modified Id', 'Modified Their Name'] end it 'shows all fields if asked' do RailsAdmin.config Fan do list do include_all_fields field PK_COLUMN field :name end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Created at', 'Updated at', 'Their Name', 'Teams'] end it 'appears in order defined' do RailsAdmin.config Fan do list do field :updated_at field :name field PK_COLUMN field :created_at end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to eq(['Updated at', 'Their Name', 'Id', 'Created at']) end it 'only lists the defined fields if some fields are defined' do RailsAdmin.config Fan do list do field PK_COLUMN field :name end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to eq(['Id', 'Their Name']) is_expected.to have_no_selector('th:nth-child(4).header') end it 'delegates the label option to the ActiveModel API' do RailsAdmin.config Fan do list do field :name end end visit index_path(model_name: 'fan') expect(find('th:nth-child(2)')).to have_content('Their Name') end it 'is renameable' do RailsAdmin.config Fan do list do field PK_COLUMN do label 'Identifier' end field :name end end visit index_path(model_name: 'fan') expect(find('th:nth-child(2)')).to have_content('Identifier') expect(find('th:nth-child(3)')).to have_content('Their Name') end it 'is renameable by type' do RailsAdmin.config Fan do list do fields_of_type :datetime do label { "#{label} (datetime)" } end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Created at (datetime)', 'Updated at (datetime)', 'Their Name', 'Teams'] end it 'is globally renameable by type' do RailsAdmin.config Fan do list do fields_of_type :datetime do label { "#{label} (datetime)" } end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Created at (datetime)', 'Updated at (datetime)', 'Their Name', 'Teams'] end it 'is sortable by default' do visit index_path(model_name: 'fan') is_expected.to have_selector('th:nth-child(2).header') is_expected.to have_selector('th:nth-child(3).header') is_expected.to have_selector('th:nth-child(4).header') is_expected.to have_selector('th:nth-child(5).header') end it 'has option to disable sortability' do RailsAdmin.config Fan do list do field PK_COLUMN do sortable false end field :name end end visit index_path(model_name: 'fan') is_expected.to have_no_selector('th:nth-child(2).header') is_expected.to have_selector('th:nth-child(3).header') end it 'has option to disable sortability by type' do RailsAdmin.config Fan do list do fields_of_type :datetime do sortable false end field PK_COLUMN field :name field :created_at field :updated_at end end visit index_path(model_name: 'fan') is_expected.to have_selector('th:nth-child(2).header') is_expected.to have_selector('th:nth-child(3).header') is_expected.to have_no_selector('th:nth-child(4).header') is_expected.to have_no_selector('th:nth-child(5).header') end it 'has option to disable sortability by type globally' do RailsAdmin.config Fan do list do fields_of_type :datetime do sortable false end field PK_COLUMN field :name field :created_at field :updated_at end end visit index_path(model_name: 'fan') is_expected.to have_selector('th:nth-child(2).header') is_expected.to have_selector('th:nth-child(3).header') is_expected.to have_no_selector('th:nth-child(4).header') is_expected.to have_no_selector('th:nth-child(5).header') end it 'has option to hide fields by type' do RailsAdmin.config Fan do list do fields_of_type :datetime do hide end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Their Name', 'Teams'] end it 'has option to hide fields by type globally' do RailsAdmin.config Fan do list do fields_of_type :datetime do hide end end end visit index_path(model_name: 'fan') expect(all('th').collect(&:text).delete_if { |t| /^\n*$/ =~ t }). to match_array ['Id', 'Their Name', 'Teams'] end it 'has option to customize column width' do RailsAdmin.config Fan do list do field PK_COLUMN do column_width 200 end field :name field :created_at field :updated_at end end @fans = FactoryBot.create_list(:fan, 2) visit index_path(model_name: 'fan') # NOTE: Capybara really doesn't want us to look at invisible text. This test # could break at any moment. expect(find('style').native.text).to include("#list th.#{PK_COLUMN}_field") expect(find('style').native.text).to include("#list td.#{PK_COLUMN}_field") end it 'has option to customize output formatting' do RailsAdmin.config Fan do list do field PK_COLUMN field :name do formatted_value do value.to_s.upcase end end field :created_at field :updated_at end end @fans = FactoryBot.create_list(:fan, 2).sort_by(&:id) visit index_path(model_name: 'fan') expect(find('tbody tr:nth-child(1) td:nth-child(3)')).to have_content(@fans[1].name.upcase) expect(find('tbody tr:nth-child(2) td:nth-child(3)')).to have_content(@fans[0].name.upcase) end it 'has a simple option to customize output formatting of date fields' do RailsAdmin.config Fan do list do field PK_COLUMN field :name field :created_at do date_format :short end field :updated_at end end @fans = FactoryBot.create_list(:fan, 2) visit index_path(model_name: 'fan') is_expected.to have_selector('tbody tr:nth-child(1) td:nth-child(4)', text: /\d{2} \w{3} \d{1,2}:\d{1,2}/) end it 'has option to customize output formatting of date fields' do RailsAdmin.config Fan do list do field PK_COLUMN field :name field :created_at do strftime_format '%Y-%m-%d' end field :updated_at end end @fans = FactoryBot.create_list(:fan, 2) visit index_path(model_name: 'fan') is_expected.to have_selector('tbody tr:nth-child(1) td:nth-child(4)', text: /\d{4}-\d{2}-\d{2}/) end it 'allows addition of virtual fields (object methods)' do RailsAdmin.config Team do list do field PK_COLUMN field :name field :player_names_truncated end end @team = FactoryBot.create :team @players = FactoryBot.create_list :player, 2, team: @team visit index_path(model_name: 'team') expect(find('tbody tr:nth-child(1) td:nth-child(4)')).to have_content(@players.sort_by(&:id).collect(&:name).join(', ')) end describe 'with title attribute' do it 'does not allow XSS' do RailsAdmin.config Team do list do field :name end end @team = FactoryBot.create :team, name: '" onclick="alert()" "' visit index_path(model_name: 'team') expect(find('tbody tr:nth-child(1) td:nth-child(2)')['onclick']).to be_nil expect(find('tbody tr:nth-child(1) td:nth-child(2)')['title']).to eq '" onclick="alert()" "' end it 'does not break values with HTML tags' do RailsAdmin.config Player do list do field :team end end @player = FactoryBot.create :player, team: FactoryBot.create(:team) visit index_path(model_name: 'player') expect(find('tbody tr:nth-child(1) td:nth-child(2)')['title']).to eq @player.team.name end end end context 'when no record exists' do before do visit index_path(model_name: 'player') end it 'shows "No records found" message' do is_expected.to have_content('No records found') end end context 'without pagination' do before do @players = FactoryBot.create_list(:player, 2) visit index_path(model_name: 'player') end it 'shows "2 results"' do is_expected.to have_content('2 players') end end context 'with pagination' do def visit_page(page) visit index_path(model_name: 'player', page: page) end before do FactoryBot.create_list :player, 3 end describe 'with limited_pagination=false' do before { RailsAdmin.config.default_items_per_page = 1 } it 'page 1' do visit_page(1) within('ul.pagination') do expect(find('li:first')).to have_content('« Prev') expect(find('li:last')).to have_content('Next »') expect(find('li.active')).to have_content('1') end end it 'page 2' do visit_page(2) within('ul.pagination') do expect(find('li:first')).to have_content('« Prev') expect(find('li:last')).to have_content('Next »') expect(find('li.active')).to have_content('2') end end it 'page 3' do visit_page(3) within('ul.pagination') do expect(find('li:first')).to have_content('« Prev') expect(find('li:last')).to have_content('Next »') expect(find('li.active')).to have_content('3') end end end context 'with limited_pagination=true' do before do RailsAdmin.config.default_items_per_page = 1 allow(RailsAdmin::AbstractModel.new(Player).config.list). to receive(:limited_pagination). and_return(true) end it 'page 1' do visit_page(1) within('ul.pagination') do expect(find('li:first')).not_to have_content('« Prev') expect(find('li:last')).to have_content('Next »') end end it 'page 2' do visit_page(2) within('ul.pagination') do expect(find('li:first')).to have_content('« Prev') expect(find('li:last')).to have_content('Next »') end end it 'page 3' do visit_page(3) within('ul.pagination') do expect(find('li:first')).to have_content('« Prev') expect(find('li:last')).to have_content('Next »') end end end describe 'number of items per page' do before do FactoryBot.create_list :league, 2 end it 'is configurable per model' do RailsAdmin.config League do list do items_per_page 1 end end visit index_path(model_name: 'league') is_expected.to have_selector('tbody tr', count: 1) visit index_path(model_name: 'player') is_expected.to have_selector('tbody tr', count: 3) end end end context 'on showing all' do it 'responds successfully with a single model' do FactoryBot.create :player visit index_path(model_name: 'player', all: true) expect(find('div.total-count')).to have_content('1 player') expect(find('div.total-count')).not_to have_content('1 players') end it 'responds successfully with multiple models' do FactoryBot.create_list(:player, 2) visit index_path(model_name: 'player', all: true) expect(find('div.total-count')).to have_content('2 players') end end context 'with pagination disabled by :associated_collection' do it 'responds successfully' do @team = FactoryBot.create :team Array.new(2) { FactoryBot.create :player, team: @team } visit index_path(model_name: 'player', associated_collection: 'players', compact: true, current_action: 'update', source_abstract_model: 'team', source_object_id: @team.id) expect(find('div.total-count')).to have_content('2 players') end end describe 'sorting' do let(:today) { Date.today } let(:players) do [{name: 'Jackie Robinson', created_at: today, team_id: rand(99_999), number: 42}, {name: 'Deibinson Romero', created_at: (today - 2.days), team_id: rand(99_999), number: 13}, {name: 'Sandy Koufax', created_at: (today - 1.days), team_id: rand(99_999), number: 32}] end let(:leagues) do [{name: 'American', created_at: (today - 1.day)}, {name: 'Florida State', created_at: (today - 2.days)}, {name: 'National', created_at: today}] end let(:player_names_by_date) { players.sort_by { |p| p[:created_at] }.collect { |p| p[:name] } } let(:league_names_by_date) { leagues.sort_by { |l| l[:created_at] }.collect { |l| l[:name] } } before { @players = players.collect { |h| Player.create(h) } } it 'has reverse direction by default' do RailsAdmin.config Player do list do sort_by :created_at field :name end end visit index_path(model_name: 'player') player_names_by_date.reverse.each_with_index do |name, i| expect(find("tbody tr:nth-child(#{i + 1})")).to have_content(name) end end it 'allows change direction by using field configuration' do RailsAdmin.config Player do list do sort_by :created_at configure :created_at do sort_reverse false end field :name end end visit index_path(model_name: 'player') player_names_by_date.each_with_index do |name, i| expect(find("tbody tr:nth-child(#{i + 1})")).to have_content(name) end end it 'can be activated by clicking the table header', js: true do visit index_path(model_name: 'player') find('th.header', text: 'Name').trigger('click') is_expected.to have_css('th.name_field.headerSortDown') expect(all('tbody td.name_field').map(&:text)).to eq @players.map(&:name).sort end end context 'on listing as compact json' do it 'has_content an array with 2 elements and contain an array of elements with keys id and label' do FactoryBot.create_list(:player, 2) get index_path(model_name: 'player', compact: true, format: :json) expect(ActiveSupport::JSON.decode(response.body).length).to eq(2) ActiveSupport::JSON.decode(response.body).each do |object| expect(object).to have_key('id') expect(object).to have_key('label') end end end describe 'with search operator' do let(:player) { FactoryBot.create :player } before do expect(Player.count).to eq(0) end it 'finds the player if the query matches the default search operator' do RailsAdmin.config do |config| config.default_search_operator = 'ends_with' config.model Player do list { field :name } end end visit index_path(model_name: 'player', query: player.name[2, -1]) is_expected.to have_content(player.name) end it 'does not find the player if the query does not match the default search operator' do RailsAdmin.config do |config| config.default_search_operator = 'ends_with' config.model Player do list { field :name } end end visit index_path(model_name: 'player', query: player.name[0, 2]) is_expected.to have_no_content(player.name) end it 'finds the player if the query matches the specified search operator' do RailsAdmin.config Player do list do field :name do search_operator 'starts_with' end end end visit index_path(model_name: 'player', query: player.name[0, 2]) is_expected.to have_content(player.name) end it 'does not find the player if the query does not match the specified search operator' do RailsAdmin.config Player do list do field :name do search_operator 'starts_with' end end end visit index_path(model_name: 'player', query: player.name[1..]) is_expected.to have_no_content(player.name) end end describe 'with custom search' do before do RailsAdmin.config do |config| config.model Player do list do search_by :rails_admin_search end end end end let!(:players) do [FactoryBot.create(:player, name: 'Joe'), FactoryBot.create(:player, name: 'George')] end it 'performs search using given scope' do visit index_path(model_name: 'player', query: 'eoJ') is_expected.to have_content(players[0].name) is_expected.to have_no_content(players[1].name) end end context 'with overridden to_param' do before do @ball = FactoryBot.create :ball visit index_path(model_name: 'ball') end it 'shows the show, edit and delete links with valid url' do is_expected.to have_selector("td a[href$='/admin/ball/#{@ball.id}']") is_expected.to have_selector("td a[href$='/admin/ball/#{@ball.id}/edit']") is_expected.to have_selector("td a[href$='/admin/ball/#{@ball.id}/delete']") end end describe 'with model scope' do context 'without default scope' do let!(:teams) { %w[red yellow blue].map { |color| FactoryBot.create :team, color: color } } it 'works', active_record: true do RailsAdmin.config do |config| config.model Team do scope { Team.where(color: %w[red blue]) } end end visit index_path(model_name: 'team') expect(all(:css, 'td.color_field').map(&:text)).to match_array %w[red blue] end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
true
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/nested_many_spec.rb
spec/integration/widgets/nested_many_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Nested many widget', type: :request, js: true do subject { page } let(:field_test) { FactoryBot.create :field_test } let(:nested_field_tests) { %w[1 2].map { |i| NestedFieldTest.create! title: "title #{i}", field_test: field_test } } before do RailsAdmin.config(FieldTest) do field :nested_field_tests end end it 'adds a new nested item' do visit edit_path(model_name: 'field_test', id: field_test.id) find('#field_test_nested_field_tests_attributes_field .add_nested_fields').click expect(page).to have_selector('.fields.tab-pane.active', visible: true) # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.nested_field_tests.length).to eq(1) end it 'edits a nested item' do nested_field_tests visit edit_path(model_name: 'field_test', id: field_test.id) fill_in 'field_test_nested_field_tests_attributes_0_title', with: 'nested field test title 1 edited', visible: false edited_id = find('#field_test_nested_field_tests_attributes_0_id', visible: false).value # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.nested_field_tests.find(edited_id).title).to eq('nested field test title 1 edited') end it 'deletes a nested item' do nested_field_tests visit edit_path(model_name: 'field_test', id: field_test.id) find('#field_test_nested_field_tests_attributes_0__destroy', visible: false).set('true') # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.reload.nested_field_tests.map(&:id)).to eq [nested_field_tests[1].id] end it 'sets bindings[:object] to nested object', js: false do RailsAdmin.config(NestedFieldTest) do nested do field :title do label do bindings[:object].class.name end end end end nested_field_tests visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('#field_test_nested_field_tests_attributes_0_title_field')).to have_content('NestedFieldTest') end it 'is deactivatable' do visit new_path(model_name: 'field_test') is_expected.to have_selector('#field_test_nested_field_tests_attributes_field .add_nested_fields') RailsAdmin.config(FieldTest) do configure :nested_field_tests do nested_form false end end visit new_path(model_name: 'field_test') is_expected.to have_no_selector('#field_test_nested_field_tests_attributes_field .add_nested_fields') end it 'is closable after adding a new item' do visit new_path(model_name: 'field_test') within('#field_test_nested_field_tests_attributes_field') do find('.add_nested_fields').click expect(page).to have_selector('.tab-content.collapse.show') expect(page).to have_selector('.nav .nav-link.active', visible: true) expect(page).to have_selector('.fields.tab-pane.active', visible: true) find(':scope > .controls .toggler').click expect(page).not_to have_selector('.tab-content.collapse.show') expect(page).not_to have_selector('.nav .nav-link.active', visible: true) expect(page).not_to have_selector('.fields.tab-pane.active', visible: true) end end it 'closes after removing all items' do visit new_path(model_name: 'field_test') within('#field_test_nested_field_tests_attributes_field') do find('.add_nested_fields').click expect(page).to have_selector('.tab-content.collapse.show') find(':scope > .tab-content > .fields > .remove_nested_fields', visible: false).click expect(page).not_to have_selector('.nav .nav-link.active', visible: true) expect(page).not_to have_selector('.fields.tab-pane.active', visible: true) end end context 'with nested_attributes_options given' do before do allow(FieldTest.nested_attributes_options).to receive(:[]).with(any_args). and_return(allow_destroy: true) end it 'does not show destroy button except for newly created when :allow_destroy is false', js: false do nested_field_tests allow(FieldTest.nested_attributes_options).to receive(:[]).with(:nested_field_tests). and_return(allow_destroy: false) visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('#field_test_nested_field_tests_attributes_0_title').value).to eq('title 1') is_expected.not_to have_selector('form .remove_nested_fields') expect(find('div#nested_field_tests_fields_blueprint', visible: false)[:'data-blueprint']).to match( /<a[^>]* class="remove_nested_fields"[^>]*>/, ) end end context "when a field which have the same name of nested_in field's" do it "does not hide fields which are not associated with nesting parent field's model" do visit new_path(model_name: 'field_test') is_expected.not_to have_selector('select#field_test_nested_field_tests_attributes_new_nested_field_tests_field_test_id') expect(find('div#nested_field_tests_fields_blueprint', visible: false)[:'data-blueprint']).to match( /<select[^>]* id="field_test_nested_field_tests_attributes_new_nested_field_tests_another_field_test_id"[^>]*>/, ) end it 'hides fields that are deeply nested with inverse_of' do visit new_path(model_name: 'field_test') expect(page.body).to_not include('field_test_nested_field_tests_attributes_new_nested_field_tests_deeply_nested_field_tests_attributes_new_deeply_nested_field_tests_nested_field_test_id_field') expect(page.body).to include('field_test_nested_field_tests_attributes_new_nested_field_tests_deeply_nested_field_tests_attributes_new_deeply_nested_field_tests_title') end end context 'when XSS attack is attempted' do it 'does not break on adding a new item' do allow(I18n).to receive(:t).and_call_original expect(I18n).to receive(:t).with('admin.form.new_model', name: 'Nested field test').and_return('<script>throw "XSS";</script>') visit edit_path(model_name: 'field_test', id: field_test.id) find('#field_test_nested_field_tests_attributes_field .add_nested_fields').click end it 'does not break on editing an existing item' do NestedFieldTest.create! title: '<script>throw "XSS";</script>', field_test: field_test visit edit_path(model_name: 'field_test', id: field_test.id) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/filtering_select_spec.rb
spec/integration/widgets/filtering_select_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Filtering select widget', type: :request, js: true do subject { page } let!(:teams) { ['Los Angeles Dodgers', 'Texas Rangers'].map { |name| FactoryBot.create :team, name: name } } let(:player) { FactoryBot.create :player, team: teams[0] } before do RailsAdmin.config Player do field :team field :number end end context 'on create' do before { visit new_path(model_name: 'player') } it 'is initially unset' do expect(find('input.ra-filtering-select-input').value).to be_empty expect(find('#player_team_id', visible: false).value).to be_empty end it 'supports filtering' do find('input.ra-filtering-select-input').set('ge') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array ['Los Angeles Dodgers', 'Texas Rangers'] find('input.ra-filtering-select-input').set('Los') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to eq ['Los Angeles Dodgers'] find('input.ra-filtering-select-input').set('Mets') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array ['No objects found'] end it 'sets id of the selected item' do find('input.ra-filtering-select-input').set('Tex') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Texas Rangers")).click()} expect(find('#player_team_id', visible: false).value).to eq teams[1].id.to_s end end context 'on update' do it 'changes the selected value' do visit edit_path(model_name: 'player', id: player.id) expect(find('#player_team_id', visible: false).value).to eq teams[0].id.to_s find('input.ra-filtering-select-input').set('Tex') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Texas Rangers")).click()} expect(find('#player_team_id', visible: false).value).to eq teams[1].id.to_s end it 'clears the current selection with making the search box empty' do visit edit_path(model_name: 'player', id: player.id) find('input.ra-filtering-select-input').set('') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keyup'))") expect(find('#player_team_id', visible: false).value).to be_empty end it 'clears the current selection with selecting the clear option' do visit edit_path(model_name: 'player', id: player.id) within('.filtering-select') { find('.dropdown-toggle').click } find('a.ui-menu-item-wrapper', text: /Clear/).click expect(find('#player_team_id', visible: false).value).to be_empty end context 'when the field is required' do before do RailsAdmin.config Player do field(:team) { required true } end visit edit_path(model_name: 'player', id: player.id) end it 'does not show the clear option' do within('.filtering-select') { find('.dropdown-toggle').click } is_expected.not_to have_css('a.ui-menu-item-wrapper', text: /Clear/) end end end it 'prevents duplication when using browser back and forward' do player visit index_path(model_name: 'player') find(%([href$="/admin/player/#{player.id}/edit"])).click is_expected.to have_content 'Edit Player' page.go_back is_expected.to have_content 'List of Players' page.go_forward is_expected.to have_content 'Edit Player' expect(all(:css, 'input.ra-filtering-select-input').count).to eq 1 end it 'does not lose options on browser back' do visit edit_path(model_name: 'player', id: player.id) find('.team_field .dropdown-toggle').click find('li.ui-menu-item a', text: /Clear/).click click_link 'Show' is_expected.to have_content 'Details for Player' page.go_back find('.team_field input.ra-filtering-select-input').set('Los') page.execute_script("document.querySelector('.team_field input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a', text: 'Los Angeles Dodgers') end context 'when using remote requests' do before do RailsAdmin.config Player do field :team do associated_collection_cache_all false end end visit new_path(model_name: 'player') end it 'supports filtering' do find('input.ra-filtering-select-input').set('ge') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array ['Los Angeles Dodgers', 'Texas Rangers'] teams[0].update name: 'Cincinnati Reds' find('input.ra-filtering-select-input').set('Red') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to eq ['Cincinnati Reds'] end end describe 'dynamic scoping' do let!(:players) { FactoryBot.create_list :player, 2, team: teams[1] } let!(:freelancer) { FactoryBot.create :player, team: nil } context 'with single field' do before do player RailsAdmin.config Draft do field :team field :player do dynamically_scope_by :team end end visit new_path(model_name: 'draft') end it 'changes selection candidates based on value of the specified field' do expect(all('#draft_player_id option', visible: false).map(&:value).filter(&:present?)).to be_empty find('[data-input-for="draft_team_id"] input.ra-filtering-select-input').set('Tex') page.execute_script(%{document.querySelector('[data-input-for="draft_team_id"] input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))}) is_expected.to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Texas Rangers")).click()} within('[data-input-for="draft_player_id"].filtering-select') { find('.dropdown-toggle').click } expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array players.map(&:name) end it 'allows filtering by blank value' do within('[data-input-for="draft_player_id"].filtering-select') { find('.dropdown-toggle').click } expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array [freelancer.name] end end context 'with multiple fields' do before do player RailsAdmin.config Draft do field :team field :player do dynamically_scope_by [:team, {round: :number}] end field :round end visit new_path(model_name: 'draft', draft: {team_id: teams[1].id}) end it 'changes selection candidates based on value of the specified fields' do fill_in 'draft[round]', with: players[1].number within('[data-input-for="draft_player_id"].filtering-select') { find('.dropdown-toggle').click } expect(all(:css, 'ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to match_array [players[1].name] end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/datetimepicker_spec.rb
spec/integration/widgets/datetimepicker_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Datetimepicker widget', type: :request, js: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :datetime_field end end end it 'is initially blank' do visit new_path(model_name: 'field_test') expect(find('[name="field_test[datetime_field]"]', visible: false).value).to be_blank expect(find('[name="field_test[datetime_field]"] + input').value).to be_blank end it 'populates the value selected by the Datetime picker into the hidden_field' do visit new_path(model_name: 'field_test') is_expected.to have_css '.form-control.flatpickr-input', visible: false page.execute_script <<-JS document.querySelector('#field_test_datetime_field')._flatpickr.setDate('2015-10-08 14:00:00'); JS expect(find('#field_test_datetime_field + input').value).to eq 'October 08, 2015 14:00' expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2015-10-08T14:00:00' end it 'populates the value entered in the text field into the hidden_field' do visit new_path(model_name: 'field_test') find('#field_test_datetime_field + input').set 'January 2, 2021 03:45' expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2021-01-02T03:45:00' expect(find('#field_test_datetime_field + input').value).to eq 'January 02, 2021 03:45' end it 'works with a different format' do RailsAdmin.config FieldTest do edit do configure(:datetime_field) { strftime_format '%Y-%m-%d' } end end visit new_path(model_name: 'field_test') find('#field_test_datetime_field + input').set '2021-01-02' expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2021-01-02T00:00:00' expect(find('#field_test_datetime_field + input').value).to eq '2021-01-02' end it 'supports custom flatpickr_format' do RailsAdmin.config FieldTest do edit do configure(:datetime_field) { flatpickr_format 'H\Hi\MS\S' } end end visit new_path(model_name: 'field_test') is_expected.to have_css '.form-control.flatpickr-input', visible: false page.execute_script <<-JS document.querySelector('#field_test_datetime_field')._flatpickr.setDate('2015-10-08 12:34:56'); JS expect(find('#field_test_datetime_field + input').value).to eq '12H34M56S' end context 'with locale set' do around(:each) do |example| original = I18n.default_locale I18n.default_locale = :fr example.run I18n.default_locale = original end it 'shows and accepts the value in the given locale' do visit new_path(model_name: 'field_test', field_test: {datetime_field: '2021-01-02T03:45:00'}) expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2021-01-02T03:45:00' expect(find('#field_test_datetime_field + input').value).to eq 'samedi 02 janvier 2021 03:45' find('#field_test_datetime_field + input').set 'mercredi 03 février 2021 04:55' expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2021-02-03T04:55:00' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/remote_form_spec.rb
spec/integration/widgets/remote_form_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Remote form widget', type: :request, js: true do subject { page } describe 'modal' do it 'supports focusing on sub-modals' do visit new_path(model_name: 'division') click_link 'Add a new League' is_expected.to have_content 'New League' is_expected.not_to have_css '#modal.modal-static' execute_script %($(document.body).append($('<div id="sub-modal" class="modal d-block"><input type="text" /></div>'))) find('#sub-modal input').click is_expected.to have_css '#sub-modal input:focus' end end context 'with filtering select widget' do let(:league) { FactoryBot.create :league } let(:division) { FactoryBot.create :division, league: league } before do RailsAdmin.config Division do field :league end RailsAdmin.config League do field :name end end it 'creates an associated record' do visit new_path(model_name: 'division') click_link 'Add a new League' is_expected.to have_content 'New League' fill_in 'Name', with: 'National League' find('#modal .save-action').click expect(find('#division_custom_league_id', visible: false).value).to eq League.first.id.to_s expect(League.pluck(:name)).to eq ['National League'] end it 'updates the associated record' do visit edit_path(model_name: 'division', id: division.id) expect(find('#division_custom_league_id', visible: false).value).to eq league.id.to_s click_link 'Edit this League' is_expected.to have_content "Edit League '#{league.name}'" fill_in 'Name', with: 'National League' find('#modal .save-action').click expect(find('#division_custom_league_id', visible: false).value).to eq league.id.to_s expect(league.reload.name).to eq 'National League' end end context 'with filtering multi-select widget' do let(:leagues) { FactoryBot.create_list :league, 2 } let!(:division) { FactoryBot.create :division, name: 'National League Central', league: leagues[0] } before do RailsAdmin.config League do field :divisions end RailsAdmin.config Division do field :name field :league end end it 'creates an associated record and adds into selection' do visit edit_path(model_name: 'league', id: leagues[1].id) click_link 'Add a new Division' is_expected.to have_content 'New Division' fill_in 'Name', with: 'National League West' find(%(#division_custom_league_id option[value="#{leagues[0].id}"]), visible: false).select_option find('#modal .save-action').click is_expected.to have_css('.ra-multiselect-selection option', text: 'National League West') new_division = Division.where(name: 'National League West').first expect(new_division).not_to be nil expect(find('#league_division_ids', visible: false).value).to eq [new_division.id.to_s] end it 'updates an unselected associated record with leaving it unselected' do visit edit_path(model_name: 'league', id: leagues[1].id) find('.ra-multiselect-collection option', text: division.name).double_click is_expected.to have_content "Edit Division 'National League Central'" fill_in 'Name', with: 'National League East' find('#modal .save-action').click is_expected.to have_css('.ra-multiselect-collection option', text: 'National League East') expect(find('#league_division_ids', visible: false).value).to eq [] expect(division.reload.name).to eq 'National League East' end it 'updates a selected associated record' do visit edit_path(model_name: 'league', id: leagues[0].id) find('.ra-multiselect-selection option', text: division.name).double_click is_expected.to have_content "Edit Division 'National League Central'" fill_in 'Name', with: 'National League East' find('#modal .save-action').click expect(find('#league_division_ids', visible: false).value).to eq [division.id.to_s] expect(division.reload.name).to eq 'National League East' end context 'with inline_edit set to false' do before do RailsAdmin.config League do field :divisions do inline_edit false end end end it 'does not open the modal with double click' do visit edit_path(model_name: 'league', id: leagues[1].id) find('.ra-multiselect-collection option', text: division.name).double_click is_expected.not_to have_content "Edit Division 'National League Central'" end end end context 'with file upload' do before do RailsAdmin.config NestedFieldTest do field :field_test end RailsAdmin.config FieldTest do field :carrierwave_asset end end it 'submits successfully' do visit new_path(model_name: 'nested_field_test') click_link 'Add a new Field test' is_expected.to have_content 'New Field test' attach_file 'Carrierwave asset', file_path('test.jpg') find('#modal .save-action').click is_expected.to have_css('option', text: /FieldTest #/, visible: false) expect(FieldTest.first.carrierwave_asset.file.size).to eq 1575 end end context 'with validation errors' do before do RailsAdmin.config Team do field :players end RailsAdmin.config Player do field :name field :number field :team end end context 'on create' do it 'shows the error messages' do visit new_path(model_name: 'team') click_link 'Add a new Player' is_expected.to have_content 'New Player' find('#player_name').set('on steroids') find('#modal .save-action').click is_expected.to have_css('#modal') is_expected.to have_content 'Player is cheating' is_expected.to have_css '.text-danger', text: 'is not a number' end end context 'on update' do let!(:player) { FactoryBot.create :player, name: 'Cheater' } it 'shows the error messages' do visit new_path(model_name: 'team') find('option', text: 'Cheater').double_click is_expected.to have_content "Edit Player 'Cheater'" find('#player_name').set('Cheater on steroids') find('#player_number').set('') find('#modal .save-action').click is_expected.to have_css('#modal') is_expected.to have_content 'Player is cheating' is_expected.to have_css '.text-danger', text: 'is not a number' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/nested_one_spec.rb
spec/integration/widgets/nested_one_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Nested one widget', type: :request, js: true do subject { page } let(:field_test) { FactoryBot.create :field_test } before do RailsAdmin.config(FieldTest) do field :comment end end it 'adds an nested item' do visit edit_path(model_name: 'field_test', id: field_test.id) find('#field_test_comment_attributes_field .add_nested_fields').click fill_in 'field_test_comment_attributes_content', with: 'nested comment content' # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.reload.comment.content.strip).to eq('nested comment content') end it 'deletes the nested item' do FactoryBot.create :comment, commentable: field_test visit edit_path(model_name: 'field_test', id: field_test.id) find('.comment_field .toggler').click find('.comment_field .remove_nested_fields', visible: false).click # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.reload.comment).to be nil end it 'is optional' do visit edit_path(model_name: 'field_test', id: field_test.id) click_button 'Save' expect(field_test.reload.comment).to be_nil end it 'is closable after adding a new item' do visit new_path(model_name: 'field_test') within('#field_test_comment_attributes_field') do find('.add_nested_fields').click expect(page).to have_selector('.tab-content.collapse.show') expect(page).to have_selector('.fields.tab-pane.active', visible: true) find(':scope > .controls .toggler').click expect(page).not_to have_selector('.tab-content.collapse.show') expect(page).not_to have_selector('.fields.tab-pane.active', visible: true) end end it 'closes after removing the item' do visit new_path(model_name: 'field_test') within('#field_test_comment_attributes_field') do find('.add_nested_fields').click expect(page).to have_selector('.tab-content.collapse.show') find(':scope > .tab-content > .fields > .remove_nested_fields', visible: false).click expect(page).not_to have_selector('.fields.tab-pane.active', visible: true) end end context 'when XSS attack is attempted' do it 'does not break on adding a new item' do allow(I18n).to receive(:t).and_call_original expect(I18n).to receive(:t).with('admin.form.new_model', name: 'Comment').and_return('<script>throw "XSS";</script>') visit edit_path(model_name: 'field_test', id: field_test.id) find('#field_test_comment_attributes_field .add_nested_fields').click end it 'does not break on adding an existing item' do RailsAdmin.config Comment do object_label_method :content end FactoryBot.create :comment, content: '<script>throw "XSS";</script>', commentable: field_test visit edit_path(model_name: 'field_test', id: field_test.id) end end context 'when the nested field contains a required field' do before do RailsAdmin.config Comment do configure :content do required true end end end it 'is not affected by form required validation' do FactoryBot.create :comment, commentable: field_test, content: '' visit edit_path(model_name: 'field_test', id: field_test.id) find('.comment_field .toggler').click find('.comment_field .remove_nested_fields', visible: false).click # trigger click via JS, workaround for instability in CI execute_script %(document.querySelector('button[name="_save"]').click()) is_expected.to have_content('Field test successfully updated') expect(field_test.reload.comment).to be nil end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/filter_box_spec.rb
spec/integration/widgets/filter_box_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Filter box widget', type: :request, js: true do subject { page } it 'adds filters' do RailsAdmin.config Player do field :name field :position end visit index_path(model_name: 'player') is_expected.to have_no_css('#filters_box .filter') click_link 'Add filter' click_link 'Name' within('#filters_box') do is_expected.to have_css('.filter', count: 1) is_expected.to have_css('.filter select[name^="f[name]"]') end click_link 'Add filter' click_link 'Position' within('#filters_box') do is_expected.to have_css('.filter', count: 2) is_expected.to have_css('.filter select[name^="f[position]"]') end end it 'removes filters' do RailsAdmin.config Player do field :name field :position end visit index_path(model_name: 'player') is_expected.to have_no_css('#filters_box .filter') click_link 'Add filter' click_link 'Name' click_link 'Add filter' click_link 'Position' within('#filters_box') do is_expected.to have_css('.filter', count: 2) click_button 'Name' is_expected.to have_no_css('.filter select[name^="f[name]"]') click_button 'Position' is_expected.to have_no_css('.filter') end end it 'hides redundant filter options for required fields' do RailsAdmin.config Player do list do field :name do required true end field :team end end visit index_path(model_name: 'player', f: {name: {'1' => {v: ''}}, team: {'2' => {v: ''}}}) within(:select, name: 'f[name][1][o]') do expect(page.all('option').map(&:value)).to_not include('_present', '_blank') end within(:select, name: 'f[team][2][o]') do expect(page.all('option').map(&:value)).to include('_present', '_blank') end end it 'supports limiting filter operators' do RailsAdmin.config Player do list do field :name do filter_operators %w[is starts_with _present] end end end visit index_path(model_name: 'player') is_expected.to have_no_css('#filters_box .filter') click_link 'Add filter' click_link 'Name' within(:select, name: /f\[name\]\[\d+\]\[o\]/) do expect(page.all('option').map(&:value)).to eq %w[is starts_with _present] end end it 'does not cause duplication when using browser back' do RailsAdmin.config Player do field :name end visit index_path(model_name: 'player', f: {name: {'1' => {v: 'a'}}}) find(%([href$="/admin/player/export"])).click is_expected.to have_content 'Export Players' page.go_back is_expected.to have_content 'List of Players' expect(all(:css, '#filters_box div.filter').count).to eq 1 end describe 'for boolean field' do before do RailsAdmin.config FieldTest do field :boolean_field end end it 'is filterable with true and false' do visit index_path(model_name: 'field_test') click_link 'Add filter' click_link 'Boolean field' within('#filters_box') do expect(page.all('option').map(&:value)).to include('true', 'false') end end end describe 'for date field' do before do RailsAdmin.config FieldTest do field :date_field end end it 'populates the value selected by the Datetimepicker into the hidden_field' do visit index_path(model_name: 'field_test') click_link 'Add filter' click_link 'Date field' expect(find('[name^="f[date_field]"][name$="[v][]"]', match: :first, visible: false).value).to be_blank page.execute_script <<-JS document.querySelector('.form-control.date')._flatpickr.setDate('2015-10-08'); JS expect(find('[name^="f[date_field]"][name$="[v][]"]', match: :first, visible: false).value).to eq '2015-10-08T00:00:00' end end describe 'for datetime field' do before do RailsAdmin.config FieldTest do field :datetime_field end end it 'populates the value selected by the Datetimepicker into the hidden_field' do visit index_path(model_name: 'field_test') click_link 'Add filter' click_link 'Datetime field' expect(find('[name^="f[datetime_field]"][name$="[v][]"]', match: :first, visible: false).value).to be_blank page.execute_script <<-JS document.querySelector('.form-control.datetime')._flatpickr.setDate('2015-10-08 14:00:00'); JS expect(find('[name^="f[datetime_field]"][name$="[v][]"]', match: :first, visible: false).value).to eq '2015-10-08T14:00:00' end end describe 'for enum field' do before do RailsAdmin.config Team do field :color, :enum end end it 'supports multiple selection mode' do visit index_path(model_name: 'team') click_link 'Add filter' click_link 'Color' expect(all('#filters_box option').map(&:text)).to include 'white', 'black', 'red', 'green', 'blu<e>é' find('.filter .switch-select .fa-plus').click expect(find('#filters_box select')['multiple']).to be true expect(find('#filters_box select')['name']).to match(/\[\]$/) end context 'with the filter pre-populated' do it 'does not break' do visit index_path(model_name: 'team', f: {color: {'1' => {v: 'red'}}}) is_expected.to have_css('.filter select[name^="f[color]"]') expect(find('.filter select[name^="f[color]"]').value).to eq 'red' expect(all('#filters_box option').map(&:text)).to include 'white', 'black', 'red', 'green', 'blu<e>é' end end end describe 'for time field', active_record: true do before do RailsAdmin.config FieldTest do field :time_field end end it 'populates the value selected by the Datetimepicker into the hidden_field' do visit index_path(model_name: 'field_test') click_link 'Add filter' click_link 'Time field' expect(find('[name^="f[time_field]"][name$="[v][]"]', match: :first, visible: false).value).to be_blank page.execute_script <<-JS document.querySelector('.form-control.datetime')._flatpickr.setDate('2000-01-01 14:00:00'); JS expect(find('[name^="f[time_field]"][name$="[v][]"]', match: :first, visible: false).value).to eq '2000-01-01T14:00:00' end end describe 'for has_one association field' do before do RailsAdmin.config Player do field :draft do searchable :college end end end it 'is filterable' do visit index_path(model_name: 'player') click_link 'Add filter' click_link 'Draft' expect(page).to have_css '[name^="f[draft]"][name$="[o]"]' expect(page).to have_css '[name^="f[draft]"][name$="[v]"]' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/widgets/filtering_multi_select_spec.rb
spec/integration/widgets/filtering_multi_select_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Filtering multi-select widget', type: :request, js: true do subject { page } let(:team) { FactoryBot.create :team } let!(:players) { ['Cory Burns', 'Leonys Martin', 'Matt Garza'].map { |name| FactoryBot.create :player, name: name } } before do RailsAdmin.config Team do field :players end end context 'on create' do before { visit new_path(model_name: 'team') } it 'is initially unset' do expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Leonys Martin', 'Cory Burns', 'Matt Garza'] expect(find('.ra-multiselect-selection').text).to be_empty end it 'supports filtering' do find('input.ra-multiselect-search').set('Alex') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_content 'No objects found' find('input.ra-multiselect-search').set('Ma') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_content 'Leonys' expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Leonys Martin', 'Matt Garza'] end it 'sets ids of the selected items' do find('.ra-multiselect-collection option', text: /Cory/).select_option within('.ra-multiselect-center') { click_link 'Add new' } expect(all('.ra-multiselect-selection option').map(&:text)).to match_array ['Cory Burns'] expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Leonys Martin', 'Matt Garza'] expect(all('#team_player_ids option', visible: false).select(&:selected?).map(&:value)).to match_array [players[0].id.to_s] end end context 'on update' do let!(:player) { FactoryBot.create :player, team: team, name: 'Elvis Andrus' } before { visit edit_path(model_name: 'team', id: team.id) } it 'additionally selects items' do expect(all('#team_player_ids option', visible: false).select(&:selected?).map(&:value)).to match_array [player.id.to_s] find('.ra-multiselect-collection option', text: /Cory/).select_option within('.ra-multiselect-center') { click_link 'Add new' } expect(all('#team_player_ids option', visible: false).select(&:selected?).map(&:value)).to match_array [players[0].id.to_s, player.id.to_s] end it 'deselects the current selection' do find('.ra-multiselect-selection option', text: /Elvis/).select_option within('.ra-multiselect-center') { click_link 'Remove' } expect(all('.ra-multiselect-selection option').map(&:text)).to be_empty expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Cory Burns', 'Leonys Martin', 'Matt Garza', 'Elvis Andrus'] expect(all('#team_player_ids option', visible: false).select(&:selected?).map(&:value)).to be_empty end end describe 'Choose all button' do it 'picks all available items' do visit edit_path(model_name: 'team', id: team.id) click_link 'Choose all' expect(all(:css, '#team_player_ids option', visible: false).map(&:value)).to match_array players.map(&:id).map(&:to_s) end end describe 'Clear all button' do let!(:player) { FactoryBot.create :player, team: team, name: 'Elvis Andrus' } it 'removes all selected items' do visit edit_path(model_name: 'team', id: team.id) find('.ra-multiselect-collection option', text: /Cory/).select_option within('.ra-multiselect-center') { click_link 'Add new' } expect(all('.ra-multiselect-selection option').map(&:text)).to match_array ['Cory Burns', 'Elvis Andrus'] click_link 'Clear all' expect(all(:css, '#team_player_ids option', visible: false).select(&:selected?).map(&:value)).to be_empty end end context 'when using remote requests' do before do RailsAdmin.config Team do field(:players) { associated_collection_cache_all false } end visit edit_path(model_name: 'team', id: team.id) end it 'supports filtering' do find('input.ra-multiselect-search').set('Alex') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_content 'No objects found' players[2].update name: 'Adam Rosales' find('input.ra-multiselect-search').set('Ma') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_content 'Leonys' expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Leonys Martin'] end describe 'Choose all button' do it 'does not pick the placeholder for selection' do click_link 'Choose all' expect(page).not_to have_css('#team_player_ids option', visible: false) expect(page).not_to have_css('.ra-multiselect-selection option') end it 'picks all available items' do find('input.ra-multiselect-search').set('Ma') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_css('.ra-multiselect-collection option', text: /Matt/) click_link 'Choose all' expect(all(:css, '#team_player_ids option', visible: false).map(&:value)).to match_array players[1..2].map(&:id).map(&:to_s) end end end it 'does not cause duplication when using browser back' do visit new_path(model_name: 'team') find(%([href$="/admin/team/export"])).click is_expected.to have_content 'Export Teams' page.go_back is_expected.to have_content 'New Team' expect(all(:css, 'input.ra-multiselect-search').count).to eq 1 end describe 'dynamic scoping' do let!(:team) { FactoryBot.create :team, division: FactoryBot.create(:division) } let(:division) { FactoryBot.create(:division) } let!(:teams) { ['Los Angeles Dodgers', 'Texas Rangers'].map { |name| FactoryBot.create :team, name: name, division: division } } before do RailsAdmin.config Team do field :name field :division end RailsAdmin.config Fan do field :division, :enum do enum { Division.pluck(:name, CI_ORM == :active_record ? :custom_id : :id).to_h } def value nil end def parse_input(params) params.delete :division end end field :teams do dynamically_scope_by :division end end visit new_path(model_name: 'fan') end it 'changes selection candidates based on value of the specified field' do expect(all('#fan_team_ids option', visible: false).map(&:value).filter(&:present?)).to be_empty select division.name, from: 'Division', visible: false find('input.ra-multiselect-search').set('e') page.execute_script("document.querySelector('input.ra-multiselect-search').dispatchEvent(new KeyboardEvent('keydown'))") is_expected.to have_content 'Dodgers' expect(all('.ra-multiselect-collection option').map(&:text)).to match_array ['Los Angeles Dodgers', 'Texas Rangers'] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/code_mirror_spec.rb
spec/integration/fields/code_mirror_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'CodeMirror field', type: :request do subject { page } it 'works without error', js: true do RailsAdmin.config Draft do edit do field :notes, :code_mirror end end expect { visit new_path(model_name: 'draft') }.not_to raise_error is_expected.to have_selector('.CodeMirror') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/multiple_file_upload_spec.rb
spec/integration/fields/multiple_file_upload_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'MultipleFileUpload field', type: :request do subject { page } before do RailsAdmin.config FieldTest do field :string_field, :multiple_file_upload do attachment do delete_value { value } def resource_url(_thumb = false) value end end delete_method 'boolean_field' reorderable true def value bindings[:object].safe_send(name)&.split end end end end let(:field_test) { FactoryBot.create :field_test, string_field: 'http://localhost/1.jpg http://localhost/2.jpg' } it 'supports deletion', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) click_link "Delete 'String field' #1" expect(page.all(:css, '[name="field_test[boolean_field][]"]:checked', visible: false).map(&:value)).to eq %w[http://localhost/1.jpg] end it 'shows a inline preview', js: true do visit new_path(model_name: 'field_test') attach_file 'String field', file_path('test.jpg') is_expected.to have_selector('#field_test_string_field_field img.preview') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/carrierwave_spec.rb
spec/integration/fields/carrierwave_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Carrierwave field', type: :request, active_record: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :string_field field :carrierwave_asset end end end it 'supports caching an uploaded file' do visit new_path(model_name: 'field_test') attach_file 'Carrierwave asset', file_path('test.jpg') fill_in 'field_test[string_field]', with: 'Invalid' click_button 'Save' expect(page).to have_content 'Field test failed to be created' fill_in 'field_test[string_field]', with: '' click_button 'Save' expect(FieldTest.first.carrierwave_asset.file).to exist end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/file_upload_spec.rb
spec/integration/fields/file_upload_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'FileUpload field', type: :request do subject { page } before do RailsAdmin.config FieldTest do field :string_field, :file_upload do delete_method 'boolean_field' def resource_url(_thumb = false) value end end end end let(:field_test) { FactoryBot.create :field_test, string_field: 'http://localhost/dummy.jpg' } it 'supports deletion', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('#field_test_boolean_field', visible: false)).not_to be_checked click_link "Delete 'String field'" expect(find('#field_test_boolean_field', visible: false)).to be_checked end it 'shows a inline preview', js: true do visit new_path(model_name: 'field_test') attach_file 'String field', file_path('test.jpg') is_expected.to have_selector('#field_test_string_field_field img.preview') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/polymorphic_assosiation_spec.rb
spec/integration/fields/polymorphic_assosiation_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'PolymorphicAssociation field', type: :request do subject { page } context 'on create' do it 'is editable', js: true do @players = ['Jackie Robinson', 'Rob Wooten'].map { |name| FactoryBot.create :player, name: name } visit new_path(model_name: 'comment') select 'Player', from: 'comment[commentable_type]' find('input.ra-filtering-select-input').set('Rob') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Jackie Robinson")).click()} click_button 'Save' is_expected.to have_content 'Comment successfully created' expect(Comment.first.commentable).to eq @players[0] end it 'uses base class for models with inheritance' do @hardball = FactoryBot.create :hardball post new_path(model_name: 'comment', comment: {commentable_type: 'Hardball', commentable_id: @hardball.id}) @comment = Comment.first expect(@comment.commentable_type).to eq 'Ball' expect(@comment.commentable).to eq @hardball end it 'clears the selected id on type change', js: true do @players = ['Jackie Robinson', 'Rob Wooten'].map { |name| FactoryBot.create :player, name: name } visit new_path(model_name: 'comment') select 'Player', from: 'comment[commentable_type]' find('input.ra-filtering-select-input').set('Rob') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Jackie Robinson")).click()} select 'Team', from: 'comment[commentable_type]' expect(find('#comment_commentable_id', visible: false).value).to eq '' end context 'when the associated model is declared in a two-level namespace' do it 'successfully saves the record', js: true do polymorphic_association_tests = ['Jackie Robinson', 'Rob Wooten'].map do |name| FactoryBot.create(:two_level_namespaced_polymorphic_association_test, name: name) end visit new_path(model_name: 'comment') select 'Polymorphic association test', from: 'comment[commentable_type]' find('input.ra-filtering-select-input').set('Rob') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Jackie Robinson")).click()} click_button 'Save' is_expected.to have_content 'Comment successfully created' expect(Comment.first.commentable).to eq polymorphic_association_tests.first end end end context 'on update' do let(:team) { FactoryBot.create :team, name: 'Los Angeles Dodgers' } let(:comment) { FactoryBot.create :comment, commentable: team } let!(:players) { ['Jackie Robinson', 'Rob Wooten', 'Scott Hairston'].map { |name| FactoryBot.create :player, name: name } } it 'is editable', js: true do visit edit_path(model_name: 'comment', id: comment.id) expect(find('select#comment_commentable_type').value).to eq 'Team' expect(find('select#comment_commentable_id', visible: false).value).to eq team.id.to_s find('input.ra-filtering-select-input').set('Los') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all('ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to eq ['Los Angeles Dodgers'] select 'Player', from: 'comment[commentable_type]' find('input.ra-filtering-select-input').set('Rob') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') expect(all('ul.ui-autocomplete li.ui-menu-item a').map(&:text)).to eq ['Rob Wooten', 'Jackie Robinson'] page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Jackie Robinson")).click()} click_button 'Save' is_expected.to have_content 'Comment successfully updated' expect(comment.reload.commentable).to eq players[0] end it 'is visible in the owning end' do visit edit_path(model_name: 'team', id: team.id) is_expected.to have_selector('select#team_comment_ids') end context 'with records in different models share the same id', js: true do let!(:players) { [FactoryBot.create(:player, id: team.id, name: 'Jackie Robinson')] } it 'clears the selected id on type change', js: true do visit edit_path(model_name: 'comment', id: comment.id) select 'Player', from: 'comment[commentable_type]' click_button 'Save' is_expected.to have_content 'Comment successfully updated' expect(comment.reload.commentable).to eq nil end it 'updates correctly', js: true do visit edit_path(model_name: 'comment', id: comment.id) select 'Player', from: 'comment[commentable_type]' find('input.ra-filtering-select-input').set('Rob') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Jackie Robinson")).click()} click_button 'Save' is_expected.to have_content 'Comment successfully updated' expect(comment.reload.commentable).to eq players[0] end end end context 'on show' do before do @player = FactoryBot.create :player @comment = FactoryBot.create :comment, commentable: @player visit show_path(model_name: 'comment', id: @comment.id) end it 'shows associated object' do is_expected.to have_css("a[href='/admin/player/#{@player.id}']") end end context 'on list' do before :each do @team = FactoryBot.create :team @comment = FactoryBot.create :comment, commentable: @team end it 'works like belongs to associations in the list view' do visit index_path(model_name: 'comment') is_expected.to have_content(@team.name) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/has_one_association_spec.rb
spec/integration/fields/has_one_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'HasOneAssociation field', type: :request do subject { page } it 'adds a related id to the has_one create draft link' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) is_expected.to have_selector("a[data-link='/admin/draft/new?draft%5Bplayer_id%5D=#{@player.id}&modal=true']") end context 'on create' do before do @draft = FactoryBot.create :draft end it 'shows selects' do visit new_path(model_name: 'player') is_expected.to have_selector('select#player_draft_id') end it 'creates an object with correct associations' do visit new_path(model_name: 'player') fill_in 'Name', with: 'Jackie Robinson' fill_in 'Number', with: @draft.player.number + 1 select("Draft ##{@draft.id}", from: 'Draft') click_button 'Save' is_expected.to have_content 'Player successfully created' @player = Player.where(name: 'Jackie Robinson').first @draft.reload expect(@player.draft).to eq(@draft) end context 'with default_value' do before do id = @draft.id RailsAdmin.config Player do configure :draft do default_value id end end end it 'shows the value as selected' do visit new_path(model_name: 'player') expect(find('select#player_draft_id').value).to eq @draft.id.to_s end end end context 'on update' do before do @drafts = FactoryBot.create_list :draft, 2 @player = FactoryBot.create :player, draft: @drafts[0] visit edit_path(model_name: 'player', id: @player.id) end it 'updates an object with correct associations' do select("Draft ##{@drafts[1].id}", from: 'Draft') click_button 'Save' @player.reload expect(@player.draft).to eq(@drafts[1]) end it 'clears the current selection' do select('', from: 'Draft') click_button 'Save' @player.reload expect(@player.draft).to be nil end end describe 'on show' do before do @player = FactoryBot.create :player @draft = FactoryBot.create :draft, player: @player visit show_path(model_name: 'player', id: @player.id) end it 'shows associated objects' do is_expected.to have_css("a[href='/admin/draft/#{@draft.id}']") end end context 'with custom primary_key option' do let(:user) { FactoryBot.create :managing_user } let!(:team) { FactoryBot.create(:managed_team) } before do RailsAdmin.config.included_models = [ManagingUser, ManagedTeam] RailsAdmin.config ManagingUser do field :team end end it 'allows update' do visit edit_path(model_name: 'managing_user', id: user.id) select(team.name, from: 'Team') click_button 'Save' is_expected.to have_content 'Managing user successfully updated' expect(ManagingUser.first.team).to eq team end context 'when fetching associated objects via xhr' do before do RailsAdmin.config ManagingUser do field(:team) { associated_collection_cache_all false } end end it 'allows update', js: true do visit edit_path(model_name: 'managing_user', id: user.id) find('input.ra-filtering-select-input').set('T') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("#{team.name}")).click()} click_button 'Save' is_expected.to have_content 'Managing user successfully updated' expect(ManagingUser.first.team).to eq team end end end context 'with composite foreign keys', composite_primary_keys: true do let(:fan) { FactoryBot.create(:fan) } let!(:fanship) { FactoryBot.create(:fanship, fan: fan) } describe 'via default field' do before do RailsAdmin.config Fan do field :name field :fanship end end it 'allows create' do visit new_path(model_name: 'fan') fill_in 'Name', with: 'someone' select("Fanship ##{fanship.id}", from: 'Fanship') click_button 'Save' is_expected.to have_content 'Fan successfully created' expect(Fan.where(name: 'someone').first.fanship.team_id).to eq fanship.team_id end it 'shows the current selection' do visit edit_path(model_name: 'fan', id: fanship.fan_id) is_expected.to have_select('Fanship', selected: "Fanship ##{fanship.id}") end end describe 'via remote-sourced field' do before do RailsAdmin.config Fan do field :name field :fanship do associated_collection_cache_all false end end end it 'allows create', js: true do visit new_path(model_name: 'fan') fill_in 'Name', with: 'someone' find('.fanship_field input.ra-filtering-select-input').set(fanship.fan_id) page.execute_script("document.querySelector('.fanship_field input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Fanship ##{fanship.id}")).click()} click_button 'Save' is_expected.to have_content 'Fan successfully created' expect(Fan.where(name: 'someone').first.fanship.team_id).to eq fanship.team_id end end describe 'via nested field' do let!(:team) { FactoryBot.create :team } before do RailsAdmin.config NestedFan do field :name field :fanship end end it 'allows update' do visit edit_path(model_name: 'nested_fan', id: fanship.fan_id) select(team.name, from: 'Team') fill_in 'Since', with: '2020-01-23' click_button 'Save' is_expected.to have_content 'Nested fan successfully updated' expect(fan.fanship.team).to eq team expect(fan.fanship.since).to eq Date.new(2020, 1, 23) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/paperclip_spec.rb
spec/integration/fields/paperclip_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Paperclip field', type: :request do subject { page } it 'shows a file upload field' do RailsAdmin.config User do edit do field :avatar end end visit new_path(model_name: 'user') is_expected.to have_selector('input#user_avatar') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/enum_spec.rb
spec/integration/fields/enum_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Enum field', type: :request, active_record: true do subject { page } before do allow_any_instance_of(Team).to receive(:color_enum).and_return(%w[blue green red]) end describe 'for single value' do before do RailsAdmin.config Team do field :color end end it 'shows a single-value edit form' do visit new_path(model_name: 'team') is_expected.to have_selector('.enum_type select') is_expected.not_to have_selector('.enum_type select[multiple]') expect(all('.enum_type option').map(&:text).select(&:present?)).to eq %w[blue green red] end it 'uses the filtering-select widget for selection', js: true do visit new_path(model_name: 'team') is_expected.to have_selector('.enum_type .filtering-select') end end describe 'for multiple values' do before do RailsAdmin.config Team do field :color do multiple true end end end it 'shows a multiple-value edit form' do visit new_path(model_name: 'team') is_expected.to have_selector('.enum_type select') is_expected.to have_selector('.enum_type select[multiple]') expect(all('.enum_type option').map(&:text).select(&:present?)).to eq %w[blue green red] end it 'uses the filtering-multiselect widget for selection', js: true do visit new_path(model_name: 'team') is_expected.to have_selector('.enum_type .ra-multiselect') end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/active_storage_spec.rb
spec/integration/fields/active_storage_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'ActiveStorage field', type: :request, active_record: true do subject { page } let(:field_test) { FactoryBot.create :field_test } before do # To suppress 'SQLite3::BusyException: database is locked' exception @original = page.driver.browser.url_blacklist # rubocop:disable Naming/InclusiveLanguage page.driver.browser.url_blacklist = [%r{/rails/active_storage/representations}] # rubocop:disable Naming/InclusiveLanguage end after { page.driver.browser.url_blacklist = @original } # rubocop:disable Naming/InclusiveLanguage describe 'direct upload', js: true do before do RailsAdmin.config FieldTest do edit do field(:active_storage_asset) { direct true } end end end it 'works' do visit edit_path(model_name: 'field_test', id: field_test.id) attach_file 'Active storage asset', file_path('test.jpg') expect_any_instance_of(ActiveStorage::DirectUploadsController).to receive(:create).and_call_original click_button 'Save' expect(page).to have_content 'Field test successfully updated' field_test.reload expect(field_test.active_storage_asset.filename).to eq 'test.jpg' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/datetime_spec.rb
spec/integration/fields/datetime_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Datetime field', type: :request do subject { page } before do RailsAdmin.config FieldTest do edit do field :datetime_field end end end describe 'filtering' do let!(:field_tests) do [FactoryBot.create(:field_test, datetime_field: DateTime.new(2021, 1, 2, 3, 45)), FactoryBot.create(:field_test, datetime_field: DateTime.new(2021, 1, 2, 4, 45))] end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {datetime_field: {'1' => {v: [nil, '2021-01-02T04:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end it 'does not break when the condition is not filled' do visit index_path(model_name: 'field_test', f: {datetime_field: {'1' => {v: [nil, '', ''], o: 'between'}}}) is_expected.to have_content '2 field test' end context 'with server timezone changed' do around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {datetime_field: {'1' => {v: [nil, '2021-01-01T22:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end end end context 'on create' do it 'is initially blank' do visit new_path(model_name: 'field_test') expect(find('[name="field_test[datetime_field]"]', visible: false).value).to be_blank end it 'persists the value' do visit new_path(model_name: 'field_test') find('[name="field_test[datetime_field]"]', visible: false).set('2021-01-02T03:45:00') click_button 'Save' expect(FieldTest.count).to eq 1 expect(FieldTest.first.datetime_field).to eq DateTime.new(2021, 1, 2, 3, 45) end end context 'on update' do let(:field_test) { FactoryBot.create :field_test, datetime_field: DateTime.new(2021, 1, 2, 3, 45) } it 'updates the value' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2021-01-02T03:45:00' find('[name="field_test[datetime_field]"]', visible: false).set('2021-02-03T04:55:00') click_button 'Save' field_test.reload expect(field_test.datetime_field).to eq DateTime.new(2021, 2, 3, 4, 55) end end context 'with server timezone changed' do let(:field_test) { FactoryBot.create :field_test, datetime_field: DateTime.new(2015, 10, 8, 6, 45) } around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'treats the datetime set by the browser as local time' do visit edit_path(model_name: 'field_test', id: field_test.id) find('[name="field_test[datetime_field]"]', visible: false).set('2021-02-03T04:55:00') click_button 'Save' field_test.reload expect(field_test.datetime_field.iso8601).to eq '2021-02-03T04:55:00-06:00' end it 'is not altered by just saving untouched' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[datetime_field]"]', visible: false).value).to eq '2015-10-08T01:45:00' click_button 'Save' expect { field_test.reload }.not_to change(field_test, :datetime_field) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/hidden_spec.rb
spec/integration/fields/hidden_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Hidden field', type: :request do subject { page } describe '#default_value' do before do RailsAdmin::Config.authenticate_with { warden.authenticate! scope: :user } RailsAdmin::Config.current_user_method(&:current_user) login_as User.create( email: 'username@example.com', password: 'password', ) end before do RailsAdmin.config Player do include_all_fields edit do field :name, :hidden do default_value do bindings[:view]._current_user.email end end end end end it 'shows up with default value, hidden' do visit new_path(model_name: 'player') is_expected.to have_selector("#player_name[type=hidden][value='username@example.com']", visible: false) is_expected.not_to have_selector("#player_name[type=hidden][value='toto@example.com']", visible: false) end it 'does not show label' do is_expected.not_to have_selector('label', text: 'Name') end it 'does not show help block' do is_expected.not_to have_xpath("id('player_name')/../p[@class='help-block']") end it 'submits the field value' do visit new_path(model_name: 'player') find("#player_name[type=hidden][value='username@example.com']", visible: false).set('someone@example.com') fill_in 'Number', with: 1 click_button 'Save' is_expected.to have_content('Player successfully created') expect(Player.first.name).to eq 'someone@example.com' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/has_and_belongs_to_many_association_spec.rb
spec/integration/fields/has_and_belongs_to_many_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'HasAndBelongsToManyAssociation field', type: :request do subject { page } context 'on create' do before do @teams = FactoryBot.create_list(:team, 3) post new_path(model_name: 'fan', fan: {name: 'John Doe', team_ids: [@teams[0].id]}) @fan = RailsAdmin::AbstractModel.new('Fan').first end it 'creates an object with correct associations' do @teams[0].reload expect(@fan.teams).to include(@teams[0]) expect(@fan.teams).not_to include(@teams[1]) expect(@fan.teams).not_to include(@teams[2]) end end describe 'on update' do before do @teams = FactoryBot.create_list(:team, 3) @fan = FactoryBot.create :fan, teams: [@teams[0]] visit edit_path(model_name: 'fan', id: @fan.id) end it 'shows associated objects' do is_expected.to have_selector '#fan_team_ids' do |select| options = select.all 'option' expect(options[0]['selected']).to eq 'selected' expect(options[1]['selected']).to eq nil expect(options[2]['selected']).to eq nil end end end describe 'on show' do before do @player = FactoryBot.create :player @comment1 = FactoryBot.create :comment, commentable: @player @comment2 = FactoryBot.create :comment, commentable: @player @comment3 = FactoryBot.create :comment, commentable: FactoryBot.create(:player) visit show_path(model_name: 'player', id: @player.id) end it 'shows associated objects' do is_expected.to have_css("a[href='/admin/comment/#{@comment1.id}']") is_expected.to have_css("a[href='/admin/comment/#{@comment2.id}']") is_expected.not_to have_css("a[href='/admin/comment/#{@comment3.id}']") end end context "with Mongoid's custom primary_key option", mongoid: true do let(:user) { FactoryBot.create :managing_user, players: [players[0]], balls: [balls[0]] } let!(:players) { FactoryBot.create_list(:player, 2) } let!(:balls) { %w[red blue].map { |color| FactoryBot.create(:ball, color: color) } } before do RailsAdmin.config ManagingUser do field :players field :balls end end it 'allows update' do visit edit_path(model_name: 'managing_user', id: user.id) expect(find("select#managing_user_player_names option[value=\"#{players[0].name}\"]")).to be_selected expect(find("select#managing_user_ball_ids option[value=\"#{balls[0].color}\"]")).to be_selected select(players[1].name, from: 'Players') select(balls[1].rails_admin_default_object_label_method, from: 'Balls') click_button 'Save' expect(ManagingUser.first.players).to match_array players expect(ManagingUser.first.balls).to match_array balls end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/multiple_carrierwave_spec.rb
spec/integration/fields/multiple_carrierwave_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'MultipleCarrierwave field', type: :request, active_record: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :carrierwave_assets end end end it 'supports uploading multiple files', js: true do visit new_path(model_name: 'field_test') attach_file 'Carrierwave assets', [file_path('test.jpg'), file_path('test.png')] click_button 'Save' is_expected.to have_content 'Field test successfully created' expect(FieldTest.first.carrierwave_assets.map { |image| File.basename(image.url) }).to match_array ['test.jpg', 'test.png'] end context 'when working with existing files' do let(:field_test) { FactoryBot.create(:field_test, carrierwave_assets: ['test.jpg', 'test.png'].map { |img| File.open(file_path(img)) }) } it 'supports appending a file', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) attach_file 'Carrierwave assets', [file_path('test.gif')] click_button 'Save' is_expected.to have_content 'Field test successfully updated' field_test.reload expect(field_test.carrierwave_assets.map { |image| File.basename(image.url) }).to eq ['test.jpg', 'test.png', 'test.gif'] end it 'supports deleting a file', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) click_link "Delete 'Carrierwave assets' #1" click_button 'Save' is_expected.to have_content 'Field test successfully updated' field_test.reload expect(field_test.carrierwave_assets.map { |image| File.basename(image.url) }).to eq ['test.png'] end it 'supports reordering files', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) page.execute_script File.read(File.expand_path('../../../vendor/assets/javascripts/rails_admin/jquery3.js', __dir__)) page.execute_script File.read(File.expand_path('../../support/jquery.simulate.drag-sortable.js', __dir__)) page.execute_script %{$(".ui-sortable-handle:first-child").simulateDragSortable({move: 1});} click_button 'Save' is_expected.to have_content 'Field test successfully updated' field_test.reload expect(field_test.carrierwave_assets.map { |image| File.basename(image.url) }).to eq ['test.png', 'test.jpg'] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/serialized_spec.rb
spec/integration/fields/serialized_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Serialized field', type: :request do subject { page } context 'with serialized objects' do before do RailsAdmin.config do |c| c.model User do configure :roles, :serialized end end @user = FactoryBot.create :user visit edit_path(model_name: 'user', id: @user.id) fill_in 'user[roles]', with: %(['admin', 'user']) click_button 'Save' # first(:button, "Save").click @user.reload end it 'saves the serialized data' do expect(@user.roles).to eq(%w[admin user]) end end context 'with serialized objects of Mongoid', mongoid: true do before do @field_test = FactoryBot.create :field_test visit edit_path(model_name: 'field_test', id: @field_test.id) end it 'saves the serialized data' do fill_in 'field_test[array_field]', with: '[4, 2]' fill_in 'field_test[hash_field]', with: '{ a: 6, b: 2 }' click_button 'Save' # first(:button, "Save").click @field_test.reload expect(@field_test.array_field).to eq([4, 2]) expect(@field_test.hash_field).to eq('a' => 6, 'b' => 2) end it 'clears data when empty string is passed' do fill_in 'field_test[array_field]', with: '' fill_in 'field_test[hash_field]', with: '' click_button 'Save' # first(:button, "Save").click @field_test.reload expect(@field_test.array_field).to eq(nil) expect(@field_test.hash_field).to eq(nil) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/has_many_association_spec.rb
spec/integration/fields/has_many_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'HasManyAssociation field', type: :request do subject { page } it 'adds a related id to the has_many create team link' do @team = FactoryBot.create :team visit edit_path(model_name: 'team', id: @team.id) is_expected.to have_selector("a[data-link='/admin/player/new?modal=true&player%5Bteam_id%5D=#{@team.id}']") end context 'when an association is readonly' do it 'is not editable' do @league = FactoryBot.create :league visit edit_path(model_name: 'league', id: @league.id) is_expected.not_to have_selector('select#league_team_ids') is_expected.to have_selector('select#league_division_ids') # decoy, fails if naming scheme changes end end describe 'has many associations through more than one association' do it 'is not editable' do @league = FactoryBot.create :league visit edit_path(model_name: 'league', id: @league.id) expect(page).to have_selector('select#league_division_ids') expect(page).to_not have_selector('select#league_player_ids') end end describe 'on create' do before do @divisions = Array.new(3) { Division.create!(name: "div #{Time.now.to_f}", league: League.create!(name: "league #{Time.now.to_f}")) } end it 'shows selects' do visit new_path(model_name: 'league') is_expected.to have_selector('select#league_division_ids') end it 'creates an object with correct associations' do post new_path(model_name: 'league', league: {name: 'National League', division_ids: [@divisions[0].id]}) @league = RailsAdmin::AbstractModel.new('League').all.to_a.last @divisions[0].reload expect(@league.divisions).to include(@divisions[0]) expect(@league.divisions).not_to include(@divisions[1]) expect(@league.divisions).not_to include(@divisions[2]) end context 'with default_value' do before do ids = [@divisions[2].id] RailsAdmin.config League do configure :divisions do default_value ids end end end it 'shows the value as selected' do visit new_path(model_name: 'league') expect(find('select#league_division_ids').value).to eq [@divisions[2].id.to_s] end end end context 'on update' do it 'is fillable and emptyable', active_record: true do @league = FactoryBot.create :league @divisions = Array.new(3) { Division.create!(name: "div #{Time.now.to_f}", league: League.create!(name: "league #{Time.now.to_f}")) } put edit_path(model_name: 'league', id: @league.id, league: {name: 'National League', division_ids: [@divisions[0].id]}) @league.reload expect(@league.name).to eq('National League') @divisions[0].reload expect(@league.divisions).to include(@divisions[0]) expect(@league.divisions).not_to include(@divisions[1]) expect(@league.divisions).not_to include(@divisions[2]) put edit_path(model_name: 'league', id: @league.id, league: {division_ids: ['']}) @league.reload expect(@league.divisions).to be_empty end context 'with embedded model', mongoid: true do it 'is editable' do @record = FactoryBot.create :field_test 2.times.each { |i| @record.embeds.create name: "embed #{i}" } visit edit_path(model_name: 'field_test', id: @record.id) fill_in 'field_test_embeds_attributes_0_name', with: 'embed 1 edited' page.find('#field_test_embeds_attributes_1__destroy', visible: false).set('true') click_button 'Save' # first(:button, "Save").click @record.reload expect(@record.embeds.length).to eq(1) expect(@record.embeds[0].name).to eq('embed 1 edited') end end end context 'on show' do context 'with embedded model', mongoid: true do it "does not show link to individual object's page" do @record = FactoryBot.create :field_test 2.times.each { |i| @record.embeds.create name: "embed #{i}" } visit show_path(model_name: 'field_test', id: @record.id) is_expected.not_to have_link('embed 0') is_expected.not_to have_link('embed 1') end end end context 'on list' do context 'with embedded model', mongoid: true do it "does not show link to individual object's page" do RailsAdmin.config FieldTest do list do field :embeds end end @record = FactoryBot.create :field_test 2.times.each { |i| @record.embeds.create name: "embed #{i}" } visit index_path(model_name: 'field_test') is_expected.not_to have_link('embed 0') is_expected.not_to have_link('embed 1') end end end context 'with not nullable foreign key', active_record: true do before do RailsAdmin.config FieldTest do edit do field :nested_field_tests do nested_form false end end end @field_test = FactoryBot.create :field_test end it 'don\'t allow to remove element', js: true do visit edit_path(model_name: 'FieldTest', id: @field_test.id) is_expected.not_to have_selector('a.ra-multiselect-item-remove') is_expected.not_to have_selector('a.ra-multiselect-item-remove-all') end end context 'with nullable foreign key', active_record: true do before do RailsAdmin.config Team do edit do field :players end end @team = FactoryBot.create :team end it 'allow to remove element', js: true do visit edit_path(model_name: 'Team', id: @team.id) is_expected.to have_selector('a.ra-multiselect-item-remove') is_expected.to have_selector('a.ra-multiselect-item-remove-all') end end context 'with custom primary_key option' do let(:user) { FactoryBot.create :managing_user } let!(:teams) { [FactoryBot.create(:managed_team, manager: user.email), FactoryBot.create(:managed_team)] } before do RailsAdmin.config.included_models = [ManagingUser, ManagedTeam] RailsAdmin.config ManagingUser do field :teams end end it 'allows update' do visit edit_path(model_name: 'managing_user', id: user.id) expect(find("select#managing_user_team_ids option[value=\"#{teams[0].id}\"]")).to have_content teams[0].name select(teams[1].name, from: 'Teams') click_button 'Save' is_expected.to have_content 'Managing user successfully updated' expect(ManagingUser.first.teams).to match_array teams end context 'when fetching associated objects via xhr' do before do RailsAdmin.config ManagingUser do field(:teams) { associated_collection_cache_all false } end end it 'allows update', js: true do visit edit_path(model_name: 'managing_user', id: user.id) find('input.ra-multiselect-search').set('T') find('.ra-multiselect-collection option', text: teams[1].name).select_option find('.ra-multiselect-item-add').click click_button 'Save' is_expected.to have_content 'Managing user successfully updated' expect(ManagingUser.first.teams).to match_array teams end end end context 'with composite foreign keys', composite_primary_keys: true do let(:fan) { FactoryBot.create(:fan) } let!(:fanships) { FactoryBot.create_list(:fanship, 3) } describe 'via default field' do before do RailsAdmin.config Fan do field :name field :fanships end end it 'shows the current selection' do visit edit_path(model_name: 'fan', id: fanships[0].fan.id) is_expected.to have_select('Fanships', selected: "Fanship ##{fanships[0].id}") end it 'allows update' do visit edit_path(model_name: 'fan', id: fan.id) select("Fanship ##{fanships[0].id}", from: 'Fanships') select("Fanship ##{fanships[1].id}", from: 'Fanships') click_button 'Save' is_expected.to have_content 'Fan successfully updated' expect(fan.reload.fanships.map(&:team_id)).to match_array fanships.map(&:team_id)[0..1] end context 'with invalid key' do before do allow_any_instance_of(RailsAdmin::Config::Fields::Types::HasManyAssociation). to receive(:collection).and_return([["Fanship ##{fanships[0].id}", 'invalid']]) end it 'fails to update' do visit edit_path(model_name: 'fan', id: fan.id) select("Fanship ##{fanships[0].id}", from: 'Fanships') expect { click_button 'Save' }.to raise_error ActiveRecord::RecordNotFound end end end describe 'via remote-sourced field' do before do RailsAdmin.config Fan do field :name field :fanships do associated_collection_cache_all false end end end it 'allows update', js: true do visit edit_path(model_name: 'fan', id: fan.id) find('input.ra-multiselect-search').set('F') find('.ra-multiselect-collection option', text: "Fanship ##{fanships[0].id}").select_option find('.ra-multiselect-collection option', text: "Fanship ##{fanships[1].id}").select_option find('.ra-multiselect-item-add').click click_button 'Save' is_expected.to have_content 'Fan successfully updated' expect(fan.reload.fanships.map(&:team_id)).to match_array fanships.map(&:team_id)[0..1] end end describe 'via nested field' do let!(:team) { FactoryBot.create :team } let!(:fanships) { FactoryBot.create_list(:fanship, 2, fan: fan) } before do RailsAdmin.config NestedFan do field :name field :fanships end end it 'allows update' do visit edit_path(model_name: 'nested_fan', id: fan.id) select(team.name, from: 'nested_fan_fanships_attributes_0_team_id') fill_in 'nested_fan_fanships_attributes_1_since', with: '2020-01-23' click_button 'Save' is_expected.to have_content 'Nested fan successfully updated' expect(fan.fanships[0].team).to eq team expect(fan.fanships[1].since).to eq Date.new(2020, 1, 23) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/ck_editor_spec.rb
spec/integration/fields/ck_editor_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'CKEditor field', type: :request do subject { page } it 'works without error', js: true do RailsAdmin.config Draft do edit do field :notes, :ck_editor end end expect { visit new_path(model_name: 'draft') }.not_to raise_error is_expected.to have_selector('#cke_draft_notes') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/action_text_spec.rb
spec/integration/fields/action_text_spec.rb
# frozen_string_literal: true require 'spec_helper' if defined?(ActionText) RSpec.describe 'ActionText field', type: :request, js: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :action_text_field end end end it 'works without error' do allow(ConsoleLogger).to receive(:warn).with(/ActionText assets should be loaded statically/) expect { visit new_path(model_name: 'field_test') }.not_to raise_error is_expected.to have_selector('trix-toolbar') end if RailsAdmin.config.asset_source == :sprockets && Rails.gem_version < Gem::Version.new('7.0') it 'shows a warning if ActionText assets are loaded dynamically' do expect(ConsoleLogger).to receive(:warn).with(/ActionText assets should be loaded statically/) visit new_path(model_name: 'field_test') is_expected.to have_selector('trix-toolbar') end it 'allows suppressing the warning' do RailsAdmin.config FieldTest do edit do field :action_text_field do warn_dynamic_load false end end end expect(ConsoleLogger).not_to receive(:warn).with(/ActionText assets should be loaded statically/) visit new_path(model_name: 'field_test') is_expected.to have_selector('trix-toolbar') end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/shrine_spec.rb
spec/integration/fields/shrine_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Shrine field', type: :request, active_record: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :string_field field :shrine_asset end end end it 'supports caching an uploaded file', js: true do visit new_path(model_name: 'field_test') attach_file 'Shrine asset', file_path('test.jpg') fill_in 'field_test[string_field]', with: 'Invalid' click_button 'Save' expect(page).to have_content 'Field test failed to be created' fill_in 'field_test[string_field]', with: '' click_button 'Save' expect(FieldTest.first.shrine_asset).to exist end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/multiple_active_storage_spec.rb
spec/integration/fields/multiple_active_storage_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'MultipleActiveStorage field', type: :request, active_record: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :active_storage_assets end end # To suppress 'SQLite3::BusyException: database is locked' exception @original = page.driver.browser.url_blacklist # rubocop:disable Naming/InclusiveLanguage page.driver.browser.url_blacklist = [%r{/rails/active_storage/representations}] # rubocop:disable Naming/InclusiveLanguage end after { page.driver.browser.url_blacklist = @original } # rubocop:disable Naming/InclusiveLanguage it 'supports uploading multiple files', js: true do visit new_path(model_name: 'field_test') attach_file 'Active storage assets', [file_path('test.jpg'), file_path('test.png')] click_button 'Save' is_expected.to have_content 'Field test successfully created' expect(FieldTest.first.active_storage_assets.map { |image| image.filename.to_s }).to match_array ['test.jpg', 'test.png'] end context 'when working with existing files' do let(:field_test) { FactoryBot.create(:field_test, active_storage_assets: ['test.jpg', 'test.png'].map { |img| {io: File.open(file_path(img)), filename: img} }) } it 'supports appending a file', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) attach_file 'Active storage assets', [file_path('test.gif')] click_button 'Save' is_expected.to have_content 'Field test successfully updated' field_test.reload expect(field_test.active_storage_assets.map { |image| image.filename.to_s }).to eq ['test.jpg', 'test.png', 'test.gif'] end it 'supports deleting a file', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) click_link "Delete 'Active storage assets' #1" click_button 'Save' is_expected.to have_content 'Field test successfully updated' field_test.reload expect(field_test.active_storage_assets.map { |image| image.filename.to_s }).to eq ['test.png'] end end describe 'direct upload', js: true do let(:field_test) { FactoryBot.create :field_test } before do RailsAdmin.config FieldTest do edit do configure(:active_storage_assets) { direct true } end end end it 'works' do visit edit_path(model_name: 'field_test', id: field_test.id) attach_file 'Active storage assets', [file_path('test.jpg')] expect_any_instance_of(ActiveStorage::DirectUploadsController).to receive(:create).and_call_original click_button 'Save' expect(page).to have_content 'Field test successfully updated' field_test.reload expect(field_test.active_storage_assets.map { |image| image.filename.to_s }).to eq ['test.jpg'] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/wysihtml5_spec.rb
spec/integration/fields/wysihtml5_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Wysihtml5 field', type: :request do subject { page } it 'works without error', js: true do RailsAdmin.config Draft do edit do field :notes, :wysihtml5 end end expect { visit new_path(model_name: 'draft') }.not_to raise_error is_expected.to have_selector('.wysihtml5-toolbar') end it 'should include custom wysihtml5 configuration' do RailsAdmin.config Draft do edit do field :notes, :wysihtml5 do config_options image: false css_location 'stub_css.css' js_location 'stub_js.js' end end end visit new_path(model_name: 'draft') is_expected.to have_selector('textarea#draft_notes[data-richtext="bootstrap-wysihtml5"][data-options]') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/color_spec.rb
spec/integration/fields/color_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Color field', type: :request do subject { page } it 'uses HTML5 color picker' do RailsAdmin.config Team do field :color, :color end visit new_path(model_name: 'team') is_expected.to have_selector('#team_color[type="color"]') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/base_spec.rb
spec/integration/fields/base_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Base field', type: :request do subject { page } describe '#default_value' do it 'is set for all types of input fields' do RailsAdmin.config do |config| config.excluded_models = [] config.model(FieldTest) do field :string_field do default_value 'string_field default_value' end field :text_field do default_value 'string_field text_field' end field :boolean_field do default_value true end field :date_field do default_value Date.today end end end visit new_path(model_name: 'field_test') # In Rails 3.2.3 behavior of textarea has changed to insert newline after the opening tag, # but Capybara's RackTest driver is not up to this behavior change. # (https://github.com/jnicklas/capybara/issues/677) # So we manually cut off first newline character as a workaround here. expect(find_field('field_test[string_field]').value.gsub(/^\n/, '')).to eq('string_field default_value') expect(find_field('field_test[text_field]').value.gsub(/^\n/, '')).to eq('string_field text_field') expect(find('[name="field_test[date_field]"]', visible: false).value).to eq(Date.today.to_s) expect(has_checked_field?('field_test[boolean_field]')).to be_truthy end it 'sets default value for selects' do RailsAdmin.config(Team) do field :color, :enum do default_value 'black' enum do %w[black white] end end end visit new_path(model_name: 'team') expect(find_field('team[color]').value).to eq('black') end it 'renders custom value next time if error happend' do RailsAdmin.config(Team) do field :name do render do raise ZeroDivisionError unless bindings[:object].persisted? 'Custom Name' end end end expect { visit new_path(model_name: 'team') }.to raise_error(/ZeroDivisionError/) record = FactoryBot.create(:team) visit edit_path(model_name: 'team', id: record.id) expect(page).to have_content('Custom Name') end end describe '#bindings' do it 'is available' do RailsAdmin.config do |config| config.excluded_models = [] end RailsAdmin.config Category do field :parent_category do visible do !bindings[:object].new_record? end end end visit new_path(model_name: 'category') is_expected.to have_no_css('#category_parent_category_id') click_button 'Save' # first(:button, "Save").click visit edit_path(model_name: 'category', id: Category.first) is_expected.to have_css('#category_parent_category_id') click_button 'Save' # first(:button, "Save").click is_expected.to have_content('Category successfully updated') end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/active_record_enum_spec.rb
spec/integration/fields/active_record_enum_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'ActiveRecordEnum field', type: :request, active_record: true do subject { page } describe 'for string-keyed enum' do before do RailsAdmin.config FieldTest do edit do field :string_enum_field do default_value 'M' end end end end it 'auto-detects enumeration' do visit new_path(model_name: 'field_test') is_expected.to have_selector('.enum_type select') is_expected.not_to have_selector('.enum_type select[multiple]') expect(all('.enum_type option').map(&:text).select(&:present?)).to eq %w[S M L] end it 'shows current value as selected' do visit edit_path(model_name: 'field_test', id: FieldTest.create(string_enum_field: 'L')) expect(find('.enum_type select').value).to eq 'l' end it 'can be updated' do visit edit_path(model_name: 'field_test', id: FieldTest.create(string_enum_field: 'S')) select 'L' click_button 'Save' expect(FieldTest.first.string_enum_field).to eq 'L' end it 'pre-populates default value' do visit new_path(model_name: 'field_test') expect(find('.enum_type select').value).to eq 'm' end end describe 'for integer-keyed enum' do before do RailsAdmin.config FieldTest do edit do field :integer_enum_field do default_value :medium end end end end it 'auto-detects enumeration' do visit new_path(model_name: 'field_test') is_expected.to have_selector('.enum_type select') is_expected.not_to have_selector('.enum_type select[multiple]') expect(all('.enum_type option').map(&:text).select(&:present?)).to eq %w[small medium large] end it 'shows current value as selected' do visit edit_path(model_name: 'field_test', id: FieldTest.create(integer_enum_field: :large)) expect(find('.enum_type select').value).to eq '2' end it 'can be updated' do visit edit_path(model_name: 'field_test', id: FieldTest.create(integer_enum_field: :small)) select 'large' click_button 'Save' expect(FieldTest.first.integer_enum_field).to eq 'large' end it 'pre-populates default value' do visit new_path(model_name: 'field_test') expect(find('.enum_type select').value).to eq '1' end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/time_spec.rb
spec/integration/fields/time_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Time field', type: :request, active_record: true do subject { page } before do RailsAdmin.config FieldTest do edit do field :time_field end end end describe 'filtering' do let!(:field_tests) do [FactoryBot.create(:field_test, time_field: DateTime.new(2000, 1, 1, 3, 45)), FactoryBot.create(:field_test, time_field: DateTime.new(2000, 1, 1, 4, 45))] end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {time_field: {'1' => {v: [nil, '2000-01-01T04:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end it 'does not break when the condition is not filled' do visit index_path(model_name: 'field_test', f: {time_field: {'1' => {v: [nil, '', ''], o: 'between'}}}) is_expected.to have_content '2 field test' end context 'with server timezone changed' do around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {time_field: {'1' => {v: [nil, '2000-01-01T22:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end end end context 'on create' do it 'is initially blank' do visit new_path(model_name: 'field_test') expect(find('[name="field_test[time_field]"]', visible: false).value).to be_blank end it 'persists the value' do visit new_path(model_name: 'field_test') find('[name="field_test[time_field]"]', visible: false).set('2000-01-01T03:45:00') click_button 'Save' expect(FieldTest.count).to eq 1 expect(FieldTest.first.time_field).to eq DateTime.new(2000, 1, 1, 3, 45) end it 'ignores the date part' do visit new_path(model_name: 'field_test') find('[name="field_test[time_field]"]', visible: false).set('2021-01-02T03:45:00') click_button 'Save' expect(FieldTest.first.time_field).to eq DateTime.new(2000, 1, 1, 3, 45) end end context 'on update' do let(:field_test) { FactoryBot.create :field_test, time_field: DateTime.new(2021, 1, 2, 3, 45) } it 'updates the value' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[time_field]"]', visible: false).value).to eq '2000-01-01T03:45:00' find('[name="field_test[time_field]"]', visible: false).set('2021-02-03T04:55:00') click_button 'Save' field_test.reload expect(field_test.time_field).to eq DateTime.new(2000, 1, 1, 4, 55) end end context 'with server timezone changed' do let(:field_test) { FactoryBot.create :field_test, time_field: DateTime.new(2000, 1, 1, 6, 45) } around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'treats the datetime set by the browser as local time' do visit edit_path(model_name: 'field_test', id: field_test.id) find('[name="field_test[time_field]"]', visible: false).set('2000-01-01T04:55:00') click_button 'Save' field_test.reload expect(field_test.time_field.iso8601).to eq '2000-01-01T04:55:00-06:00' end it 'is not altered by just saving untouched' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[time_field]"]', visible: false).value).to eq '2000-01-01T00:45:00' click_button 'Save' expect { field_test.reload }.not_to change(field_test, :time_field) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/belongs_to_association_spec.rb
spec/integration/fields/belongs_to_association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'BelongsToAssociation field', type: :request do subject { page } it 'does not add a related id to the belongs_to create team link' do @player = FactoryBot.create :player visit edit_path(model_name: 'player', id: @player.id) is_expected.to have_selector("a[data-link='/admin/team/new?modal=true']") end describe 'on create' do let!(:draft) { FactoryBot.create :draft } let(:team) { FactoryBot.create :team } it 'shows selects' do visit new_path(model_name: 'player') is_expected.to have_selector('select#player_team_id') end context 'with default_value' do before do id = team.id RailsAdmin.config Player do configure :team do default_value id end end end it 'shows the value as selected' do visit new_path(model_name: 'player') expect(find('select#player_team_id').value).to eq team.id.to_s end end end describe 'on show' do before do @team = FactoryBot.create :team @player = FactoryBot.create :player, team_id: @team.id visit show_path(model_name: 'player', id: @player.id) end it 'shows associated objects' do is_expected.to have_css("a[href='/admin/team/#{@team.id}']") end end context 'with custom primary_key option' do let(:users) { FactoryBot.create_list :managing_user, 2 } let!(:teams) { [FactoryBot.create(:managed_team, manager: users[0].email), FactoryBot.create(:managed_team)] } before do RailsAdmin.config.included_models = [ManagedTeam, ManagingUser] RailsAdmin.config ManagedTeam do field :user end end it 'allows update' do visit edit_path(model_name: 'managed_team', id: teams[0].id) expect(page).to have_css("select#managed_team_manager option[value=\"#{users[0].email}\"]") select("ManagingUser ##{users[1].id}", from: 'User') click_button 'Save' teams[0].reload expect(teams[0].user).to eq users[1] end context 'when fetching associated objects via xhr' do before do RailsAdmin.config ManagedTeam do field(:user) { associated_collection_cache_all false } end end it 'allows update', js: true do visit edit_path(model_name: 'managed_team', id: teams[0].id) find('input.ra-filtering-select-input').set('M') page.execute_script("document.querySelector('input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("ManagingUser ##{users[1].id}")).click()} click_button 'Save' teams[0].reload expect(teams[0].user).to eq users[1] end end end context 'with composite foreign keys', composite_primary_keys: true do let!(:fanship) { FactoryBot.create(:fanship) } let(:favorite_player) { FactoryBot.create(:favorite_player) } describe 'via default field' do it 'allows update' do visit edit_path(model_name: 'favorite_player', id: favorite_player.id) is_expected.to have_select('Fanship', selected: "Fanship ##{favorite_player.fanship.id}") select("Fanship ##{fanship.id}", from: 'Fanship') click_button 'Save' is_expected.to have_content 'Favorite player successfully updated' expect(FavoritePlayer.all.map(&:fanship)).to eq [fanship] end context 'with invalid key' do before do allow_any_instance_of(RailsAdmin::Config::Fields::Types::BelongsToAssociation). to receive(:collection).and_return([["Fanship ##{fanship.id}", 'invalid']]) end it 'fails to update' do visit edit_path(model_name: 'favorite_player', id: favorite_player.id) select("Fanship ##{fanship.id}", from: 'Fanship') click_button 'Save' is_expected.to have_content 'Fanship must exist' end end end describe 'via remote-sourced field' do before do RailsAdmin.config FavoritePlayer do field :fanship do associated_collection_cache_all false end end end it 'allows update', js: true do visit edit_path(model_name: 'favorite_player', id: favorite_player.id) find('.fanship_field input.ra-filtering-select-input').set(fanship.fan_id) page.execute_script("document.querySelector('.fanship_field input.ra-filtering-select-input').dispatchEvent(new KeyboardEvent('keydown'))") expect(page).to have_selector('ul.ui-autocomplete li.ui-menu-item a') page.execute_script %{[...document.querySelectorAll('ul.ui-autocomplete li.ui-menu-item')].find(e => e.innerText.includes("Fanship ##{fanship.id}")).click()} click_button 'Save' is_expected.to have_content 'Favorite player successfully updated' expect(FavoritePlayer.all.map(&:fanship)).to eq [fanship] end end describe 'via nested field' do it 'allows update' do visit edit_path(model_name: 'nested_favorite_player', id: favorite_player.id) fill_in 'Since', with: '2020-01-23' click_button 'Save' is_expected.to have_content 'Nested favorite player successfully updated' expect(favorite_player.reload.fanship.since).to eq Date.new(2020, 1, 23) end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/boolean_spec.rb
spec/integration/fields/boolean_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Boolean field', type: :request do subject { page } let(:field_test) { FactoryBot.create :field_test } context 'if nullable' do before do RailsAdmin.config FieldTest do field :boolean_field end end it 'shows 3 radio buttons' do visit new_path(model_name: 'field_test') is_expected.to have_content 'New Field test' expect(all('[name="field_test[boolean_field]"]').map { |e| e['value'] }).to eq ['1', '0', ''] end it 'can be updated' do visit edit_path(model_name: 'field_test', id: field_test.id) # change the value to true and assert the values find('.boolean_type label.success').click click_button 'Save and edit' # validate that the success button rendered and is active expect(page).to have_selector('.boolean_type input[value="1"][checked]') # validate the value is true expect(field_test.reload.boolean_field).to be true # change the value to false and assert the values find('.boolean_type label.danger').click click_button 'Save and edit' expect(page).to have_selector('.boolean_type input[value="0"][checked]') expect(field_test.reload.boolean_field).to be false # change the value to nil and assert the values find('.boolean_type label.default').click click_button 'Save and edit' expect(page).to have_selector('.boolean_type input[value=""][checked]') expect(field_test.reload.boolean_field).to be nil end end context 'when the boolean is in an embedded document' do before do RailsAdmin.config FieldTest do field :comment end RailsAdmin.config Comment do field :content, :boolean end end it 'can be updated', js: true do visit edit_path(model_name: 'field_test', id: field_test.id) # toggle open the embedded document section find('#field_test_comment_attributes_field .add_nested_fields').click # set the value to false and assert the values find('.boolean_type label.danger').click click_button 'Save and edit' expect(field_test.reload.comment.content).to eq '0' end end context 'if not nullable' do before do RailsAdmin.config FieldTest do field :boolean_field do nullable false end end end it 'shows a checkbox' do visit new_path(model_name: 'field_test') is_expected.to have_content 'New Field test' is_expected.to have_css '[type="checkbox"][name="field_test[boolean_field]"]' end it 'can be updated' do visit edit_path(model_name: 'field_test', id: field_test.id) find('.boolean_type input').check click_button 'Save and edit' expect(field_test.reload.boolean_field).to be true find('.boolean_type input').uncheck click_button 'Save and edit' expect(field_test.reload.boolean_field).to be false end end context 'if the database column is not nullable', active_record: true do before do RailsAdmin.config FieldTest do field :non_nullable_boolean_field end end it 'shows a checkbox' do visit new_path(model_name: 'field_test') is_expected.to have_content 'New Field test' is_expected.to have_css '[type="checkbox"][name="field_test[non_nullable_boolean_field]"]' end it 'can be updated' do visit edit_path(model_name: 'field_test', id: field_test.id) find('.boolean_type input').check click_button 'Save and edit' expect(field_test.reload.non_nullable_boolean_field).to be true find('.boolean_type input').uncheck click_button 'Save and edit' expect(field_test.reload.non_nullable_boolean_field).to be false end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/simple_mde_spec.rb
spec/integration/fields/simple_mde_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'SimpleMDE field', type: :request do subject { page } it 'works without error', js: true do RailsAdmin.config Draft do edit do field :notes, :simple_mde end end expect { visit new_path(model_name: 'draft') }.not_to raise_error is_expected.to have_selector('a[title="Markdown Guide"]') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/date_spec.rb
spec/integration/fields/date_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Date field', type: :request do subject { page } before do RailsAdmin.config FieldTest do field :id field :date_field end end describe 'filtering' do let!(:field_tests) do [FactoryBot.create(:field_test, date_field: Date.new(2021, 1, 2)), FactoryBot.create(:field_test, date_field: Date.new(2021, 1, 3))] end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {date_field: {'1' => {v: [nil, '2021-01-03T00:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end it 'does not break when the condition is not filled' do visit index_path(model_name: 'field_test', f: {date_field: {'1' => {v: [nil, '', ''], o: 'between'}}}) is_expected.to have_content '2 field test' end context 'with server timezone changed' do around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'correctly returns a record' do visit index_path(model_name: 'field_test', f: {date_field: {'1' => {v: [nil, '2021-01-03T00:00:00', nil], o: 'between'}}}) is_expected.to have_content '1 field test' is_expected.to have_content field_tests[1].id end end end context 'on create' do it 'is initially blank' do visit new_path(model_name: 'field_test') expect(find('[name="field_test[date_field]"]', visible: false).value).to be_blank end it 'persists the value' do visit new_path(model_name: 'field_test') find('[name="field_test[date_field]"]', visible: false).set('2021-01-02T00:00:00') click_button 'Save' expect(FieldTest.count).to eq 1 expect(FieldTest.first.date_field).to eq Date.new(2021, 1, 2) end it 'ignores the time part' do visit new_path(model_name: 'field_test') find('[name="field_test[date_field]"]', visible: false).set('2021-01-02T12:34:00') click_button 'Save' expect(FieldTest.count).to eq 1 expect(FieldTest.first.date_field).to eq Date.new(2021, 1, 2) end end context 'on update' do let(:field_test) { FactoryBot.create :field_test, date_field: Date.new(2021, 1, 2) } it 'updates the value' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[date_field]"]', visible: false).value).to eq '2021-01-02T00:00:00' find('[name="field_test[date_field]"]', visible: false).set('2021-02-03T00:00:00') click_button 'Save' field_test.reload expect(field_test.date_field).to eq Date.new(2021, 2, 3) end end context 'with server timezone changed' do let(:field_test) { FactoryBot.create :field_test, date_field: Date.new(2015, 10, 8) } around do |example| original = Time.zone Time.zone = ActiveSupport::TimeZone.new('Central Time (US & Canada)') example.run Time.zone = original end it 'is not altered by just saving untouched' do visit edit_path(model_name: 'field_test', id: field_test.id) expect(find('[name="field_test[date_field]"]', visible: false).value).to eq '2015-10-08T00:00:00' click_button 'Save' expect { field_test.reload }.not_to change(field_test, :date_field) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/integration/fields/floara_spec.rb
spec/integration/fields/floara_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Floara field', type: :request do subject { page } it 'works without error', js: true do RailsAdmin.config Draft do edit do field :notes, :froala end end expect { visit new_path(model_name: 'draft') }.not_to raise_error is_expected.to have_selector('.fr-box') end it 'should include custom froala configuration' do RailsAdmin.config Draft do edit do field :notes, :froala do config_options inlineMode: false css_location 'stub_css.css' js_location 'stub_js.js' end end end visit new_path(model_name: 'draft') is_expected.to have_selector('textarea#draft_notes[data-richtext="froala-wysiwyg"][data-options]') end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/helpers/rails_admin/main_helper_spec.rb
spec/helpers/rails_admin/main_helper_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::MainHelper, type: :helper do describe '#rails_admin_form_for' do let(:html_form) do helper.rails_admin_form_for(FieldTest.new, url: new_path(model_name: 'field_test')) {} end let(:html_form_with_attrs) do helper.rails_admin_form_for(FieldTest.new, url: new_path(model_name: 'field_test'), html: {class: 'example'}) {} end context 'with html5 browser_validations enabled' do before do RailsAdmin.config.browser_validations = true RailsAdmin.config FieldTest do field :address, :string do required true end end end it 'should not add novalidate attribute to the html form tag' do expect(html_form).to_not include 'novalidate' end end context 'with html5 browser_validations disabled' do before do RailsAdmin.config.browser_validations = false RailsAdmin.config FieldTest do field :address, :string do required true end end end it 'should add novalidate attribute to the html form tag' do expect(html_form).to include 'novalidate="novalidate"' end it 'should add novalidate attribute to the html form tag with html attributes' do expect(html_form_with_attrs).to include 'novalidate="novalidate"' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/helpers/rails_admin/form_builder_spec.rb
spec/helpers/rails_admin/form_builder_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::FormBuilder', type: :helper do describe '#generate' do before do RailsAdmin.config Player do create do include_all_fields field :number, :hidden end end allow(helper).to receive(:authorized?).and_return(true) (@object = Player.new).save @builder = RailsAdmin::FormBuilder.new(:player, @object, helper, {}) allow(@builder).to receive(:field_for).and_return('field') action = double allow(action).to receive(:enabled?).and_return true helper.instance_variable_set :@action, action end it 'does not add additional error div from default ActionView::Base.field_error_proc' do expect(@builder.generate(action: :create, model_config: RailsAdmin.config(Player))).not_to have_css('.field_with_errors') expect(@builder.generate(action: :create, model_config: RailsAdmin.config(Player))).to have_css('.control-group.error') end it 'hidden fields should be wrapper' do expect(@builder.generate(action: :create, model_config: RailsAdmin.config(Player))).to match('control-group row mb-3 hidden_type number_field') end end describe '#object_infos' do before do allow(helper).to receive(:authorized?).and_return(true) @object = Fan.create!(name: 'foo') @builder = RailsAdmin::FormBuilder.new(:fan, @object, helper, {}) end it 'returns a tag with infos' do expect(@builder.object_infos).to eql '<span style="display:none" class="object-infos" data-model-label="Fan" data-object-label="foo"></span>' end context 'when object_label\'s type is symbol' do before { @object.name = :foo } it 'does not break' do expect(@builder.object_infos).to eql '<span style="display:none" class="object-infos" data-model-label="Fan" data-object-label="foo"></span>' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/helpers/rails_admin/application_helper_spec.rb
spec/helpers/rails_admin/application_helper_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::ApplicationHelper, type: :helper do describe '#authorized?' do let(:abstract_model) { RailsAdmin.config(FieldTest).abstract_model } it 'doesn\'t use unpersisted objects' do expect(helper).to receive(:action).with(:edit, abstract_model, nil).and_call_original helper.authorized?(:edit, abstract_model, FactoryBot.build(:field_test)) end end describe 'with #authorized? stubbed' do before do allow(controller).to receive(:authorized?).and_return(true) end describe '#current_action?' do it 'returns true if current_action, false otherwise' do @action = RailsAdmin::Config::Actions.find(:index) expect(helper.current_action?(RailsAdmin::Config::Actions.find(:index))).to be_truthy expect(helper.current_action?(RailsAdmin::Config::Actions.find(:show))).not_to be_truthy end end describe '#action' do it 'returns action by :custom_key' do RailsAdmin.config do |config| config.actions do dashboard do custom_key :my_custom_dashboard_key end end end expect(helper.action(:my_custom_dashboard_key)).to be end it 'returns only visible actions' do RailsAdmin.config do |config| config.actions do dashboard do visible false end end end expect(helper.action(:dashboard)).to be_nil end it 'returns only visible actions, passing all bindings' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Team.new)).to be expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Player.new)).to be_nil expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Player), Team.new)).to be_nil end end describe '#actions' do it 'returns actions by type' do abstract_model = RailsAdmin::AbstractModel.new(Player) object = FactoryBot.create :player expect(helper.actions(:all, abstract_model, object).collect(&:custom_key)).to eq(%i[dashboard index show new edit export delete bulk_delete history_show history_index show_in_app]) expect(helper.actions(:root, abstract_model, object).collect(&:custom_key)).to eq([:dashboard]) expect(helper.actions(:collection, abstract_model, object).collect(&:custom_key)).to eq(%i[index new export bulk_delete history_index]) expect(helper.actions(:member, abstract_model, object).collect(&:custom_key)).to eq(%i[show edit delete history_show show_in_app]) end it 'only returns visible actions, passing bindings correctly' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Team.new).collect(&:custom_key)).to eq([:test_bindings]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Player.new).collect(&:custom_key)).to eq([]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Player), Team.new).collect(&:custom_key)).to eq([]) end end describe '#logout_method' do it 'defaults to :delete when Devise is not defined' do allow(Object).to receive(:defined?).with(Devise).and_return(false) expect(helper.logout_method).to eq(:delete) end it 'uses first sign out method from Devise when it is defined' do allow(Object).to receive(:defined?).with(Devise).and_return(true) expect(Devise).to receive(:sign_out_via).and_return(%i[whatever_defined_on_devise something_ignored]) expect(helper.logout_method).to eq(:whatever_defined_on_devise) end end describe '#wording_for' do it 'gives correct wording even if action is not visible' do RailsAdmin.config do |config| config.actions do index do visible false end end end expect(helper.wording_for(:menu, :index)).to eq('List') end it 'passes correct bindings' do expect(helper.wording_for(:title, :edit, RailsAdmin::AbstractModel.new(Team), Team.new(name: 'the avengers'))).to eq("Edit Team 'the avengers'") end it 'defaults correct bindings' do @action = RailsAdmin::Config::Actions.find :edit @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = Team.new(name: 'the avengers') expect(helper.wording_for(:title)).to eq("Edit Team 'the avengers'") end it 'does not try to use the wrong :label_metod' do @abstract_model = RailsAdmin::AbstractModel.new(Draft) @object = Draft.new expect(helper.wording_for(:link, :new, RailsAdmin::AbstractModel.new(Team))).to eq('Add a new Team') end end describe '#breadcrumb' do it 'gives us a breadcrumb' do @action = RailsAdmin::Config::Actions.find(:edit, abstract_model: RailsAdmin::AbstractModel.new(Team), object: FactoryBot.create(:team, name: 'the avengers')) bc = helper.breadcrumb expect(bc).to match(/Dashboard/) # dashboard expect(bc).to match(/Teams/) # list expect(bc).to match(/the avengers/) # show expect(bc).to match(/Edit/) # current (edit) end end describe '#menu_for' do it 'passes model and object as bindings and generates a menu, excluding non-get actions' do RailsAdmin.config do |config| config.actions do dashboard index do visible do bindings[:abstract_model].model == Team end end show do visible do bindings[:object].instance_of?(Team) end end delete do http_methods %i[post put delete] end end end @action = RailsAdmin::Config::Actions.find :show @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = FactoryBot.create(:team, name: 'the avengers') expect(helper.menu_for(:root)).to match(/Dashboard/) expect(helper.menu_for(:collection, @abstract_model)).to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).to match(/Show/) @abstract_model = RailsAdmin::AbstractModel.new(Player) @object = Player.new expect(helper.menu_for(:collection, @abstract_model)).not_to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).not_to match(/Show/) end it 'excludes non-get actions' do RailsAdmin.config do |config| config.actions do dashboard do http_methods %i[post put delete] end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) end it 'shows actions which are marked as show_in_menu' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_menu: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_menu false end root :shown_in_menu, :dashboard do action_name :dashboard show_in_menu true end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) expect(helper.menu_for(:root)).to match(/Look this/) end it 'should render allow an action to have link_target as config' do RailsAdmin.config do |config| config.actions do dashboard index show do link_target :_blank end end end @action = RailsAdmin::Config::Actions.find :show @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = FactoryBot.create(:team, name: 'the avengers') expect(helper.menu_for(:member, @abstract_model, @object)).to match(/_blank/) end end describe '#main_navigation' do it 'shows included models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] end expect(helper.main_navigation).to match(/(btn-toggle).*(Navigation).*(Balls).*(Comments)/m) end it 'does not draw empty navigation labels' do RailsAdmin.config do |config| config.included_models = [Ball, Comment, Comment::Confirmed] config.model Comment do navigation_label 'Commentz' end config.model Comment::Confirmed do label_plural 'Confirmed' end end expect(helper.main_navigation).to match(/(btn-toggle).*(Navigation).*(Balls).*(Commentz).*(Confirmed)/m) expect(helper.main_navigation).not_to match(/(btn-toggle).*(Navigation).*(Balls).*(Commentz).*(Confirmed).*(Comment)/m) end it 'does not show unvisible models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] config.model Comment do hide end end result = helper.main_navigation expect(result).to match(/(btn-toggle).*(Navigation).*(Balls)/m) expect(result).not_to match('Comments') end it 'shows children of hidden models' do # https://github.com/railsadminteam/rails_admin/issues/978 RailsAdmin.config do |config| config.included_models = [Ball, Hardball] config.model Ball do hide end end expect(helper.main_navigation).to match(/(btn-toggle).*(Navigation).*(Hardballs)/m) end it 'shows children of excluded models' do RailsAdmin.config do |config| config.included_models = [Hardball] end expect(helper.main_navigation).to match(/(btn-toggle).*(Navigation).*(Hardballs)/m) end it 'nests in navigation label' do RailsAdmin.config do |config| config.included_models = [Comment] config.model Comment do navigation_label 'commentable' end end expect(helper.main_navigation).to match(/(btn-toggle).*(commentable).*(Comments)/m) end it 'nests in parent model' do RailsAdmin.config do |config| config.included_models = [Player, Comment] config.model Comment do parent Player end end expect(helper.main_navigation).to match(/(Players).* (nav-level-1).*(Comments)/m) end it 'orders' do RailsAdmin.config do |config| config.included_models = [Player, Comment] end expect(helper.main_navigation).to match(/(Comments).*(Players)/m) RailsAdmin.config(Comment) do weight 1 end expect(helper.main_navigation).to match(/(Players).*(Comments)/m) end end describe '#root_navigation' do it 'shows actions which are marked as show_in_sidebar' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_sidebar: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar false end root :shown_in_sidebar, :dashboard do action_name :dashboard show_in_sidebar true end end end expect(helper.root_navigation).not_to match(/Dashboard/) expect(helper.root_navigation).to match(/Look this/) end it 'allows grouping by sidebar_label' do I18n.backend.store_translations( :en, admin: { actions: { foo: {menu: 'Foo'}, bar: {menu: 'Bar'}, }, } ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar true sidebar_label 'One' end root :foo, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end root :bar, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end end end expect(helper.strip_tags(helper.root_navigation).delete(' ')).to eq 'OneDashboardTwoFooBar' end end describe '#static_navigation' do it 'shows not show static nav if no static links defined' do RailsAdmin.config do |config| config.navigation_static_links = {} end expect(helper.static_navigation).to be_empty end it 'shows links if defined' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Link/) end it 'shows default header if navigation_static_label not defined in config' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(I18n.t('admin.misc.navigation_static_label')) end it 'shows custom header if defined' do RailsAdmin.config do |config| config.navigation_static_label = 'Test Header' config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Header/) end end describe '#bulk_menu' do it 'includes all visible bulkable actions' do RailsAdmin.config do |config| config.actions do index collection :zorg do bulkable true action_name :zorg_action end collection :blub do bulkable true visible do bindings[:abstract_model].model == Team end end end end # Preload all models to prevent I18n being cleared in Mongoid builds RailsAdmin::AbstractModel.all en = {admin: {actions: { zorg: {bulk_link: 'Zorg all these %{model_label_plural}'}, blub: {bulk_link: 'Blub all these %{model_label_plural}'}, }}} I18n.backend.store_translations(:en, en) @abstract_model = RailsAdmin::AbstractModel.new(Team) result = helper.bulk_menu expect(result).to match('zorg_action') expect(result).to match('Zorg all these Teams') expect(result).to match('blub') expect(result).to match('Blub all these Teams') result_2 = helper.bulk_menu(RailsAdmin::AbstractModel.new(Player)) expect(result_2).to match('zorg_action') expect(result_2).to match('Zorg all these Players') expect(result_2).not_to match('blub') expect(result_2).not_to match('Blub all these Players') end end describe '#edit_user_link' do subject { helper.edit_user_link } let(:user) { FactoryBot.create(:user) } before { allow(helper).to receive(:_current_user).and_return(user) } it 'shows the edit action link of the user' do is_expected.to match(%r{href="[^"]+/admin/user/#{user.id}/edit"}) end it 'shows the gravatar icon' do is_expected.to include('gravatar') end context "when the user doesn't have the email column" do let(:user) { FactoryBot.create(:player) } it 'shows nothing' do is_expected.to be nil end end context 'when gravatar is disabled' do before { RailsAdmin.config.show_gravatar = false } it "doesn't show the gravatar icon" do is_expected.not_to include('gravatar') end end context 'when the user is not authorized to perform edit' do before do allow_any_instance_of(RailsAdmin::Config::Actions::Edit).to receive(:authorized?).and_return(false) end it 'shows gravatar and email without a link' do is_expected.to include('gravatar') is_expected.to include(user.email) is_expected.not_to match('href') end it 'shows only email without a link when gravatar is disabled' do RailsAdmin.config do |config| config.show_gravatar = false end is_expected.not_to include('gravatar') is_expected.not_to match('href') is_expected.to include(user.email) is_expected.to match("<span class=\"nav-link\"><span>#{user.email}</span></span>") end end end end describe '#flash_alert_class' do it 'makes errors red with alert-danger' do expect(helper.flash_alert_class('error')).to eq('alert-danger') end it 'makes alerts yellow with alert-warning' do expect(helper.flash_alert_class('alert')).to eq('alert-warning') end it 'makes notices blue with alert-info' do expect(helper.flash_alert_class('notice')).to eq('alert-info') end it 'prefixes others with "alert-"' do expect(helper.flash_alert_class('foo')).to eq('alert-foo') end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/controllers/rails_admin/main_controller_spec.rb
spec/controllers/rails_admin/main_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::MainController, type: :controller do routes { RailsAdmin::Engine.routes } def get(action, params) super action, params: params end before do controller.instance_variable_set :@action, RailsAdmin::Config::Actions.find(:index) end describe '#check_for_cancel' do before do allow(controller).to receive(:back_or_index) { raise StandardError.new('redirected back') } end it 'redirects to back if params[:bulk_ids] is nil when params[:bulk_action] is present' do expect { get :bulk_delete, model_name: 'player', bulk_action: 'bulk_delete' }.to raise_error('redirected back') end it 'does not redirect to back if params[:bulk_ids] and params[:bulk_action] is present' do expect { get :bulk_delete, model_name: 'player', bulk_action: 'bulk_delete', bulk_ids: [1] }.not_to raise_error end end describe '#get_sort_hash' do context 'options sortable is a hash' do before do RailsAdmin.config('Player') do configure :team do sortable do :'team.name' end end end end it 'returns the option with no changes' do controller.params = {sort: 'team', model_name: 'players'} expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))).to eq(sort: :'team.name', sort_reverse: true) end end context 'when default sort_by points to a field with a table reference for sortable' do before do RailsAdmin.config('Player') do base do field :name do sortable 'teams.name' end end list do sort_by :name end end end it 'returns the query referenced in the sortable' do expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))).to eq(sort: 'teams.name', sort_reverse: true) end end context 'with a virtual field' do before do RailsAdmin.config('Player') do base do field :virtual do sortable :name end end list do sort_by :virtual end end end it 'returns the query referenced in the sortable' do expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))).to match(sort: /["`]?players["`]?\.["`]?name["`]?/, sort_reverse: true) end end it 'works with belongs_to associations with label method virtual' do controller.params = {sort: 'parent_category', model_name: 'categories'} expect(controller.send(:get_sort_hash, RailsAdmin.config(Category))).to eq(sort: 'categories.parent_category_id', sort_reverse: true) end context 'using mongoid', mongoid: true do it 'gives back the remote table with label name, as it does not support joins' do controller.params = {sort: 'team', model_name: 'players'} expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))).to match(sort: 'players.team_id', sort_reverse: true) end end context 'using active_record', active_record: true do let(:connection_config) do if ActiveRecord::Base.respond_to?(:connection_db_config) ActiveRecord::Base.connection_db_config.configuration_hash else ActiveRecord::Base.connection_config end end it 'gives back the local column' do controller.params = {sort: 'team', model_name: 'players'} expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))).to match(sort: /^["`]teams["`]\.["`]name["`]$/, sort_reverse: true) end it 'quotes the table and column names it returns as :sort' do controller.params = {sort: 'team', model_name: 'players'} case connection_config[:adapter] when 'mysql2' expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))[:sort]).to eq '`teams`.`name`' else expect(controller.send(:get_sort_hash, RailsAdmin.config(Player))[:sort]).to eq '"teams"."name"' end end end end describe '#bulk_action' do before do RailsAdmin.config do |config| config.actions do dashboard index do visible do raise # This shouldn't be invoked end end bulk_delete end end end it 'retrieves actions using :bulkable scope' do expect { post :bulk_action, params: {model_name: 'player', bulk_action: 'bulk_delete', bulk_ids: [1]} }.not_to raise_error end end describe '#list_entries called from view' do before do @teams = FactoryBot.create_list(:team, 21) controller.params = {model_name: 'teams'} end it 'paginates' do expect(controller.list_entries(RailsAdmin.config(Team), :index, nil, false).to_a.length).to eq(21) expect(controller.list_entries(RailsAdmin.config(Team), :index, nil, true).to_a.length).to eq(20) end end describe '#list_entries called from view with kaminari custom param_name' do before do @teams = FactoryBot.create_list(:team, 21) controller.params = {model_name: 'teams'} Kaminari.config.param_name = :pagina end after do Kaminari.config.param_name = :page end it 'paginates' do expect(controller.list_entries(RailsAdmin.config(Team), :index, nil, false).to_a.length).to eq(21) expect(controller.list_entries(RailsAdmin.config(Team), :index, nil, true).to_a.length).to eq(20) end end describe '#list_entries called with bulk_ids' do before do @teams = FactoryBot.create_list(:team, 21) controller.params = {model_name: 'teams', bulk_action: 'bulk_delete', bulk_ids: @teams.collect(&:id)} end it 'does not paginate' do expect(controller.list_entries(RailsAdmin.config(Team), :bulk_delete).to_a.length).to eq(21) end end describe '#list_entries for associated_collection' do before do @team = FactoryBot.create :team controller.params = {associated_collection: 'players', current_action: 'update', source_abstract_model: 'team', source_object_id: @team.id, model_name: 'player', action: 'index'} controller.get_model # set @model_config for Team end it "doesn't scope associated collection records when associated_collection_scope is nil" do @players = FactoryBot.create_list(:player, 2) RailsAdmin.config Team do field :players do associated_collection_scope false end end expect(controller.list_entries.to_a.length).to eq(@players.size) end it 'scopes associated collection records according to associated_collection_scope' do @players = FactoryBot.create_list(:player, 4) RailsAdmin.config Team do field :players do associated_collection_scope do proc { |scope| scope.limit(3) } end end end expect(controller.list_entries.to_a.length).to eq(3) end it 'scopes associated collection records according to bindings' do @team.revenue = BigDecimal('3') @team.save @players = FactoryBot.create_list(:player, 5) RailsAdmin.config Team do field :players do associated_collection_scope do team = bindings[:object] proc do |scope| scope.limit(team.revenue) end end end end expect(controller.list_entries.to_a.length).to eq(@team.revenue.to_i) end it 'limits associated collection records number to 30 if cache_all is false' do @players = FactoryBot.create_list(:player, 40) RailsAdmin.config Team do field :players do associated_collection_cache_all false end end expect(controller.list_entries.to_a.length).to eq(30) end it "doesn't limit associated collection records number to 30 if cache_all is true" do @players = FactoryBot.create_list(:player, 40) RailsAdmin.config Team do field :players do associated_collection_cache_all true end end expect(controller.list_entries.length).to eq(@players.size) end it 'orders associated collection records by id, descending' do @players = FactoryBot.create_list(:player, 3) expect(controller.list_entries.to_a).to eq(@players.sort_by(&:id).reverse) end end describe '#action_missing' do it 'raises error when action is not found' do expect(RailsAdmin::Config::Actions).to receive(:find).and_return(nil) expect { get :index, model_name: 'player' }.to raise_error AbstractController::ActionNotFound end end describe '#respond_to_missing?' do it 'returns the result based on existence of action' do expect(controller.send(:respond_to_missing?, :index, false)).to be true expect(controller.send(:respond_to_missing?, :invalid_action, false)).to be false end end describe '#get_collection' do let(:team) { FactoryBot.create :team } let!(:player) { FactoryBot.create :player, team: team } let(:model_config) { RailsAdmin.config(Team) } let(:abstract_model) { model_config.abstract_model } before do controller.params = {model_name: 'team'} end it 'performs eager-loading with `eager_load true`' do RailsAdmin.config Team do field :players do eager_load true end end expect(abstract_model).to receive(:all).with(hash_including(include: [:players]), nil).once.and_call_original controller.send(:get_collection, model_config, nil, false).to_a end it 'performs eager-loading with custom eager_load value' do RailsAdmin.config Team do field :players do eager_load players: :draft end end expect(abstract_model).to receive(:all).with(hash_including(include: [{players: :draft}]), nil).once.and_call_original controller.send(:get_collection, model_config, nil, false).to_a end context 'on export' do before do controller.instance_variable_set :@action, RailsAdmin::Config::Actions.find(:export) end it 'uses the export section' do RailsAdmin.config Team do export do field :players do eager_load true end end end expect(abstract_model).to receive(:all).with(hash_including(include: [:players]), nil).once.and_call_original controller.send(:get_collection, model_config, nil, false).to_a end end end describe 'index' do it "uses target model's primary key" do @user = FactoryBot.create :managing_user @team = FactoryBot.create :managed_team, user: @user get :index, model_name: 'managed_team', source_object_id: @user.id, source_abstract_model: 'managing_user', associated_collection: 'teams', current_action: :create, compact: true, format: :json expect(response.body).to match(/"id":"#{@team.id}"/) end context 'as JSON' do it 'returns strings' do FactoryBot.create :player, team: (FactoryBot.create :team) get :index, model_name: 'player', source_object_id: Team.first.id, source_abstract_model: 'team', associated_collection: 'players', current_action: :create, compact: true, format: :json expect(JSON.parse(response.body).first['id']).to be_a_kind_of String end end context 'when authorizing requests with pundit' do if defined?(Devise::Test) include Devise::Test::ControllerHelpers else include Devise::TestHelpers end controller(RailsAdmin::MainController) do include defined?(::Pundit::Authorization) ? ::Pundit::Authorization : ::Pundit after_action :verify_authorized end it 'performs authorization' do RailsAdmin.config do |c| c.authorize_with(:pundit) c.authenticate_with { warden.authenticate! scope: :user } c.current_user_method(&:current_user) end login_as FactoryBot.create :user, roles: [:admin] player = FactoryBot.create :player, team: (FactoryBot.create :team) expect { get :show, model_name: 'player', id: player.id }.not_to raise_error end end end describe 'sanitize_params_for!' do context 'with datetime' do before do ActionController::Parameters.permit_all_parameters = false RailsAdmin.config Comment do configure :created_at do show end end RailsAdmin.config NestedFieldTest do configure :created_at do show end end controller.params = ActionController::Parameters.new( 'field_test' => { 'unallowed_field' => "I shouldn't be here", 'datetime_field' => '2010-08-01T00:00:00', 'nested_field_tests_attributes' => { 'new_1330520162002' => { 'comment_attributes' => { 'unallowed_field' => "I shouldn't be here", 'created_at' => '2010-08-02T00:00:00', }, 'created_at' => '2010-08-03T00:00:00', }, }, 'comment_attributes' => { 'unallowed_field' => "I shouldn't be here", 'created_at' => '2010-08-04T00:00:00', }, }, ) controller.send(:sanitize_params_for!, :create, RailsAdmin.config(FieldTest), controller.params['field_test']) end after do ActionController::Parameters.permit_all_parameters = true end it 'sanitize params recursively in nested forms' do expect(controller.params[:field_test].to_h).to eq( 'datetime_field' => ::Time.zone.parse('Sun, 01 Aug 2010 00:00:00 UTC +00:00'), 'nested_field_tests_attributes' => { 'new_1330520162002' => { 'comment_attributes' => { 'created_at' => ::Time.zone.parse('Mon, 02 Aug 2010 00:00:00 UTC +00:00'), }, 'created_at' => ::Time.zone.parse('Tue, 03 Aug 2010 00:00:00 UTC +00:00'), }, }, 'comment_attributes' => { 'created_at' => ::Time.zone.parse('Wed, 04 Aug 2010 00:00:00 UTC +00:00'), }, ) end it 'enforces permit!' do expect(controller.params['field_test'].permitted?).to be_truthy expect(controller.params['field_test']['nested_field_tests_attributes'].values.first.permitted?).to be_truthy expect(controller.params['field_test']['comment_attributes'].permitted?).to be_truthy end end it 'allows for delete method with Carrierwave' do RailsAdmin.config FieldTest do field :carrierwave_asset field :carrierwave_assets field :dragonfly_asset field :paperclip_asset do delete_method :delete_paperclip_asset end if defined?(ActiveStorage) field :active_storage_asset do delete_method :remove_active_storage_asset end end if defined?(ActiveStorage) field :active_storage_assets do delete_method :remove_active_storage_assets end end if defined?(Shrine) field :shrine_asset do delete_method :remove_shrine_asset end end end controller.params = HashWithIndifferentAccess.new( 'field_test' => { 'carrierwave_asset' => 'test', 'carrierwave_asset_cache' => 'test', 'remove_carrierwave_asset' => 'test', 'carrierwave_assets' => 'test', 'dragonfly_asset' => 'test', 'remove_dragonfly_asset' => 'test', 'retained_dragonfly_asset' => 'test', 'paperclip_asset' => 'test', 'delete_paperclip_asset' => 'test', 'should_not_be_here' => 'test', }.merge(defined?(ActiveStorage) ? {'active_storage_asset' => 'test', 'remove_active_storage_asset' => 'test', 'active_storage_assets' => 'test', 'remove_active_storage_assets' => 'test'} : {}). merge(defined?(Shrine) ? {'shrine_asset' => 'test', 'remove_shrine_asset' => 'test'} : {}), ) controller.send(:sanitize_params_for!, :create, RailsAdmin.config(FieldTest), controller.params['field_test']) expect(controller.params[:field_test].to_h).to eq({ 'carrierwave_asset' => 'test', 'remove_carrierwave_asset' => 'test', 'carrierwave_asset_cache' => 'test', 'carrierwave_assets' => 'test', 'dragonfly_asset' => 'test', 'remove_dragonfly_asset' => 'test', 'retained_dragonfly_asset' => 'test', 'paperclip_asset' => 'test', 'delete_paperclip_asset' => 'test', }.merge(defined?(ActiveStorage) ? {'active_storage_asset' => 'test', 'remove_active_storage_asset' => 'test', 'active_storage_assets' => 'test', 'remove_active_storage_assets' => 'test'} : {}). merge(defined?(Shrine) ? {'shrine_asset' => 'test', 'remove_shrine_asset' => 'test'} : {})) end it 'allows for polymorphic associations parameters' do RailsAdmin.config Comment do field :commentable end controller.params = HashWithIndifferentAccess.new( 'comment' => { 'commentable_id' => 'test', 'commentable_type' => 'test', }, ) controller.send(:sanitize_params_for!, :create, RailsAdmin.config(Comment), controller.params['comment']) expect(controller.params[:comment].to_h).to eq( 'commentable_id' => 'test', 'commentable_type' => 'test', ) end end describe 'back_or_index' do before do allow(controller).to receive(:index_path).and_return(index_path) end let(:index_path) { '/' } it 'returns back to index when return_to is not defined' do controller.params = {} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to return_to url when it starts with same protocol and host' do return_to_url = "http://#{request.host}/teams" controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(return_to_url) end it 'returns back to return_to url when it contains a path' do return_to_url = '/teams' controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(return_to_url) end it 'returns back to index path when return_to path does not start with slash' do return_to_url = 'teams' controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to url does not start with full protocol' do return_to_url = "#{request.host}/teams" controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to url starts with double slash' do return_to_url = "//#{request.host}/teams" controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to url starts with triple slash' do return_to_url = "///#{request.host}/teams" controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to url does not have host' do return_to_url = 'http:///teams' controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to url starts with different protocol' do return_to_url = "other://#{request.host}/teams" controller.params = {return_to: return_to_url} expect(controller.send(:back_or_index)).to eq(index_path) end it 'returns back to index path when return_to does not start with the same protocol and host' do controller.params = {return_to: "http://google.com?#{request.host}"} expect(controller.send(:back_or_index)).to eq(index_path) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/controllers/rails_admin/application_controller_spec.rb
spec/controllers/rails_admin/application_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::ApplicationController, type: :controller do describe '#to_model_name' do it 'works with modules' do expect(controller.to_model_name('conversations~conversation')).to eq('Conversations::Conversation') end end describe 'helper method _get_plugin_name' do it 'works by default' do expect(controller.send(:_get_plugin_name)).to eq(['Dummy App', 'Admin']) end it 'works for static names' do RailsAdmin.config do |config| config.main_app_name = %w[static value] end expect(controller.send(:_get_plugin_name)).to eq(%w[static value]) end it 'works for dynamic names in the controller context' do RailsAdmin.config do |config| config.main_app_name = proc { |controller| [Rails.application.engine_name&.titleize, controller.params[:action].titleize] } end controller.params[:action] = 'dashboard' expect(controller.send(:_get_plugin_name)).to eq(['Dummy App Application', 'Dashboard']) end end describe '#_current_user' do it 'is public' do expect { controller._current_user }.not_to raise_error end end describe '#rails_admin_controller?' do it 'returns true' do expect(controller.send(:rails_admin_controller?)).to be true end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/version_spec.rb
spec/rails_admin/version_spec.rb
# frozen_string_literal: true require 'fileutils' require 'spec_helper' RSpec.describe 'RailsAdmin::Version' do describe '#warn_with_js_version' do it 'does nothing when the versions match' do allow(RailsAdmin::Version).to receive(:actual_js_version).and_return('3.0.0') allow(RailsAdmin::Version).to receive(:js).and_return('3.0.0') expect(RailsAdmin::Version).not_to receive(:warn) RailsAdmin::Version.warn_with_js_version end it "shows a warning when actual_js_version couldn't detected" do allow(RailsAdmin::Version).to receive(:actual_js_version).and_return(nil) allow(RailsAdmin::Version).to receive(:js).and_return('3.0.1') expect(RailsAdmin::Version).to receive(:warn).with(/yarn install/) RailsAdmin::Version.warn_with_js_version end it 'shows a warning when the versions do not match' do allow(RailsAdmin::Version).to receive(:actual_js_version).and_return('3.0.0') allow(RailsAdmin::Version).to receive(:js).and_return('3.0.1') expect(RailsAdmin::Version).to receive(:warn).with(/inconsistency/) RailsAdmin::Version.warn_with_js_version end end describe '#js_version_from_node_modules' do unless CI_ASSET == :sprockets let(:path) { Rails.root.join('node_modules/rails_admin/package.json') } before do @backup = File.read(path) FileUtils.rm(path) end after { File.write(path, @backup) } it 'returns nil when RailsAdmin package.json is not found' do expect(RailsAdmin::Version.send(:js_version_from_node_modules)).to be_nil end it 'shows a warning when RailsAdmin package.json is not found' do File.write(path, '{"version": "0.1.0-alpha"}') expect(RailsAdmin::Version.send(:js_version_from_node_modules)).to eq '0.1.0-alpha' end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/abstract_model_spec.rb
spec/rails_admin/abstract_model_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::AbstractModel do describe '.all' do it 'returns abstract models for all models' do expect(RailsAdmin::AbstractModel.all.map(&:model)).to include Player, Team end it 'does not pick up a model without table', active_record: true do expect(RailsAdmin::AbstractModel.all.map(&:model)).not_to include WithoutTable end end describe '.new' do context 'on ActiveRecord::NoDatabaseError', active_record: true do before do expect(WithoutTable).to receive(:table_exists?).and_raise(ActiveRecord::NoDatabaseError) end it 'does not raise error and returns nil' do expect(RailsAdmin::AbstractModel.new('WithoutTable')).to eq nil end end context 'on ActiveRecord::ConnectionNotEstablished', active_record: true do before do expect(WithoutTable).to receive(:table_exists?).and_raise(ActiveRecord::ConnectionNotEstablished) end it 'does not raise error and returns nil' do expect(RailsAdmin::AbstractModel.new('WithoutTable')).to eq nil end end end describe '#to_s' do it 'returns model\'s name' do expect(RailsAdmin::AbstractModel.new(Cms::BasicPage).to_s).to eq Cms::BasicPage.to_s end end describe '#to_param' do it 'turns namespaces into prefixes with ~' do expect(RailsAdmin::AbstractModel.new('Cms::BasicPage').to_param).to eq('cms~basic_page') end end describe 'filters' do before do @abstract_model = RailsAdmin::AbstractModel.new('FieldTest') end context 'ActiveModel::ForbiddenAttributesProtection' do it 'is present' do @abstract_model.model.ancestors.collect(&:to_s).include?('ActiveModel::ForbiddenAttributesProtection') end end context 'on ActiveRecord native enum', active_record: true do shared_examples 'filter on enum' do before do %w[S M L].each do |size| FactoryBot.create(:field_test, string_enum_field: size) end %w[small medium large].each do |size| FactoryBot.create(:field_test, integer_enum_field: size) end end let(:model) { RailsAdmin::AbstractModel.new('FieldTest') } let(:filters) { {enum_field => {'1' => {v: filter_value, o: 'is'}}} } subject(:elements) { model.all(filters: filters) } it 'lists elements by value' do expect(elements.count).to eq(expected_elements_count) expect(elements.map(&enum_field.to_sym)).to all(eq(enum_label)) end end context 'when enum is integer enum' do it_behaves_like 'filter on enum' do let(:filter_value) { 0 } let(:enum_field) { 'integer_enum_field' } let(:enum_label) { 'small' } let(:expected_elements_count) { 1 } end end context 'when enum is string enum where label <> value' do it_behaves_like 'filter on enum' do let(:filter_value) { 's' } let(:enum_field) { 'string_enum_field' } let(:enum_label) { 'S' } let(:expected_elements_count) { 1 } end end end context 'on dates' do before do [Date.new(2012, 1, 1), Date.new(2012, 1, 2), Date.new(2012, 1, 3), Date.new(2012, 1, 4)].each do |date| FactoryBot.create(:field_test, date_field: date) end end it 'lists elements within outbound limits' do expect(@abstract_model.all(filters: {'date_field' => {'1' => {v: ['', '2012-01-02', '2012-01-03'], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'date_field' => {'1' => {v: ['', '2012-01-02', '2012-01-02'], o: 'between'}}}).count).to eq(1) expect(@abstract_model.all(filters: {'date_field' => {'1' => {v: ['', '2012-01-03', ''], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'date_field' => {'1' => {v: ['', '', '2012-01-02'], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'date_field' => {'1' => {v: ['2012-01-02'], o: 'default'}}}).count).to eq(1) end end context 'on datetimes' do before do I18n.locale = :en FactoryBot.create(:field_test, datetime_field: Time.zone.local(2012, 1, 1, 23, 59, 59)) FactoryBot.create(:field_test, datetime_field: Time.zone.local(2012, 1, 2, 0, 0, 0)) FactoryBot.create(:field_test, datetime_field: Time.zone.local(2012, 1, 3, 23, 59, 59)) FactoryBot.create(:field_test, datetime_field: Time.zone.local(2012, 1, 4, 0, 0, 0)) end it 'lists elements within outbound limits' do expect(@abstract_model.all(filters: {'datetime_field' => {'1' => {v: ['', '2012-01-02T00:00:00', '2012-01-03T23:59:59'], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'datetime_field' => {'1' => {v: ['', '2012-01-02T00:00:00', '2012-01-03T12:00:00'], o: 'between'}}}).count).to eq(1) expect(@abstract_model.all(filters: {'datetime_field' => {'1' => {v: ['', '2012-01-03T12:00:00', ''], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'datetime_field' => {'1' => {v: ['', '', '2012-01-02T12:00:00'], o: 'between'}}}).count).to eq(2) expect(@abstract_model.all(filters: {'datetime_field' => {'1' => {v: ['2012-01-02T00:00:00'], o: 'default'}}}).count).to eq(1) end end end context 'with Kaminari' do before do @paged = Player.page(1) Kaminari.config.page_method_name = :per_page_kaminari @abstract_model = RailsAdmin::AbstractModel.new('Player') end after do Kaminari.config.page_method_name = :page end it "supports pagination when Kaminari's page_method_name is customized" do expect(Player).to receive(:per_page_kaminari).once.and_return(@paged) @abstract_model.all(sort: PK_COLUMN, page: 1, per: 2) end end describe 'each_associated_children' do before do @abstract_model = RailsAdmin::AbstractModel.new('Player') @draft = FactoryBot.build :draft @comments = FactoryBot.build_list :comment, 2 @player = FactoryBot.build :player, draft: @draft, comments: @comments end it 'should return has_one and has_many associations with its children' do @abstract_model.each_associated_children(@player) do |association, children| expect(children).to eq case association.name when :draft [@draft] when :comments @comments end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/active_record_extension_spec.rb
spec/rails_admin/active_record_extension_spec.rb
# frozen_string_literal: true require 'spec_helper' require File.expand_path('../../config/initializers/active_record_extensions', __dir__) RSpec.describe 'ActiveRecord::Base', active_record: true do describe '#safe_send' do it 'only calls #read_attribute once' do @player = Player.new @player.number = 23 original_method = @player.method(:read_attribute) expect(@player).to receive(:read_attribute).exactly(1).times do |*args| original_method.call(*args) end expect(@player.safe_send(:number)).to eq(23) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/config_spec.rb
spec/rails_admin/config_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config do describe '.included_models' do it 'only uses included models' do RailsAdmin.config.included_models = [Team, League] expect(RailsAdmin::AbstractModel.all.collect(&:model)).to eq([League, Team]) # it gets sorted end it 'does not restrict models if included_models is left empty' do RailsAdmin.config.included_models = [] expect(RailsAdmin::AbstractModel.all.collect(&:model)).to include(Team, League) end it 'removes excluded models (whitelist - blacklist)' do RailsAdmin.config.excluded_models = [Team] RailsAdmin.config.included_models = [Team, League] expect(RailsAdmin::AbstractModel.all.collect(&:model)).to eq([League]) end it 'excluded? returns true for any model not on the list' do RailsAdmin.config.included_models = [Team, League] team_config = RailsAdmin::AbstractModel.new('Team').config fan_config = RailsAdmin::AbstractModel.new('Fan').config expect(fan_config).to be_excluded expect(team_config).not_to be_excluded end end describe '.add_extension' do before do silence_warnings do RailsAdmin.const_set('EXTENSIONS', []) end end it 'registers the extension with RailsAdmin' do RailsAdmin.add_extension(:example, ExampleModule) expect(RailsAdmin::EXTENSIONS.count { |name| name == :example }).to eq(1) end context 'given an extension with an authorization adapter' do it 'registers the adapter' do RailsAdmin.add_extension(:example, ExampleModule, authorization: true) expect(RailsAdmin::AUTHORIZATION_ADAPTERS[:example]).to eq(ExampleModule::AuthorizationAdapter) end end context 'given an extension with an auditing adapter' do it 'registers the adapter' do RailsAdmin.add_extension(:example, ExampleModule, auditing: true) expect(RailsAdmin::AUDITING_ADAPTERS[:example]).to eq(ExampleModule::AuditingAdapter) end end context 'given an extension with a configuration adapter' do it 'registers the adapter' do RailsAdmin.add_extension(:example, ExampleModule, configuration: true) expect(RailsAdmin::CONFIGURATION_ADAPTERS[:example]).to eq(ExampleModule::ConfigurationAdapter) end end end describe '.main_app_name' do it 'as a default meaningful dynamic value' do expect(RailsAdmin.config.main_app_name.call).to eq(['Dummy App', 'Admin']) end it 'can be configured' do RailsAdmin.config do |config| config.main_app_name = %w[static value] end expect(RailsAdmin.config.main_app_name).to eq(%w[static value]) end end describe '.authorize_with' do context 'given a key for a extension with authorization' do before do RailsAdmin.add_extension(:example, ExampleModule, authorization: true) end it 'initializes the authorization adapter' do expect(ExampleModule::AuthorizationAdapter).to receive(:new).with(RailsAdmin::Config) RailsAdmin.config do |config| config.authorize_with(:example) end RailsAdmin.config.authorize_with.call end it 'passes through any additional arguments to the initializer' do options = {option: true} expect(ExampleModule::AuthorizationAdapter).to receive(:new).with(RailsAdmin::Config, options) RailsAdmin.config do |config| config.authorize_with(:example, options) end RailsAdmin.config.authorize_with.call end end end describe '.audit_with' do context 'given a key for a extension with auditing' do before do RailsAdmin.add_extension(:example, ExampleModule, auditing: true) end it 'initializes the auditing adapter' do expect(ExampleModule::AuditingAdapter).to receive(:new).with(RailsAdmin::Config) RailsAdmin.config do |config| config.audit_with(:example) end RailsAdmin.config.audit_with.call end it 'passes through any additional arguments to the initializer' do options = {option: true} expect(ExampleModule::AuditingAdapter).to receive(:new).with(RailsAdmin::Config, options) RailsAdmin.config do |config| config.audit_with(:example, options) end RailsAdmin.config.audit_with.call end end context 'given paper_trail as the extension for auditing', active_record: true do before do class ControllerMock def set_paper_trail_whodunnit; end end module PaperTrail; end class Version; end RailsAdmin.add_extension(:example, RailsAdmin::Extensions::PaperTrail, auditing: true) end it 'initializes the auditing adapter' do RailsAdmin.config do |config| config.audit_with(:example) end expect { ControllerMock.new.instance_eval(&RailsAdmin.config.audit_with) }.not_to raise_error end end end describe '.configure_with' do context 'given a key for a extension with configuration' do before do RailsAdmin.add_extension(:example, ExampleModule, configuration: true) end it 'initializes configuration adapter' do expect(ExampleModule::ConfigurationAdapter).to receive(:new) RailsAdmin.config do |config| config.configure_with(:example) end end it 'yields the (optionally) provided block, passing the initialized adapter' do configurator = nil RailsAdmin.config do |config| config.configure_with(:example) do |configuration_adapter| configurator = configuration_adapter end end expect(configurator).to be_a(ExampleModule::ConfigurationAdapter) end end end describe '.config' do context '.default_search_operator' do it 'sets the default_search_operator' do RailsAdmin.config do |config| config.default_search_operator = 'starts_with' end expect(RailsAdmin::Config.default_search_operator).to eq('starts_with') end it 'errors on unrecognized search operator' do expect do RailsAdmin.config do |config| config.default_search_operator = 'random' end end.to raise_error(ArgumentError, "Search operator 'random' not supported") end it "defaults to 'default'" do expect(RailsAdmin::Config.default_search_operator).to eq('default') end end end describe '.visible_models' do it 'passes controller bindings, find visible models, order them' do RailsAdmin.config do |config| config.included_models = [Player, Fan, Comment, Team] config.model Player do hide end config.model Fan do weight(-1) show end config.model Comment do visible do bindings[:controller]._current_user.role == :admin end end config.model Team do visible do bindings[:controller]._current_user.role != :admin end end end expect(RailsAdmin.config.visible_models(controller: double(_current_user: double(role: :admin), authorized?: true)).collect(&:abstract_model).collect(&:model)).to match_array [Fan, Comment] end it 'hides unallowed models' do RailsAdmin.config do |config| config.included_models = [Comment] end expect(RailsAdmin.config.visible_models(controller: double(authorization_adapter: double(authorized?: true))).collect(&:abstract_model).collect(&:model)).to eq([Comment]) expect(RailsAdmin.config.visible_models(controller: double(authorization_adapter: double(authorized?: false))).collect(&:abstract_model).collect(&:model)).to eq([]) end it 'does not contain embedded model', mongoid: true do RailsAdmin.config do |config| config.included_models = [FieldTest, Comment, Embed] end expect(RailsAdmin.config.visible_models(controller: double(_current_user: double(role: :admin), authorized?: true)).collect(&:abstract_model).collect(&:model)).to match_array [FieldTest, Comment] end it 'basically does not contain embedded model except model using recursively_embeds_many or recursively_embeds_one', mongoid: true do class RecursivelyEmbedsOne include Mongoid::Document recursively_embeds_one end class RecursivelyEmbedsMany include Mongoid::Document recursively_embeds_many end RailsAdmin.config do |config| config.included_models = [FieldTest, Comment, Embed, RecursivelyEmbedsMany, RecursivelyEmbedsOne] end expect(RailsAdmin.config.visible_models(controller: double(_current_user: double(role: :admin), authorized?: true)).collect(&:abstract_model).collect(&:model)).to match_array [FieldTest, Comment, RecursivelyEmbedsMany, RecursivelyEmbedsOne] end end describe '.models_pool' do it 'should not include classnames start with Concerns::' do expect(RailsAdmin::Config.models_pool.select { |m| m.match(/^Concerns::/) }).to be_empty end it 'includes models in the directory added by config.eager_load_paths' do expect(RailsAdmin::Config.models_pool).to include('Basketball') end it 'should include a model which was configured explicitly' do RailsAdmin::Config.model 'PaperTrail::Version' do visible false end expect(RailsAdmin::Config.models_pool).to include('PaperTrail::Version') end end describe '.parent_controller' do before do class TestController < ActionController::Base; end end it 'uses default class' do expect(RailsAdmin.config.parent_controller).to eq '::ActionController::Base' end it 'uses other class' do RailsAdmin.config do |config| config.parent_controller = 'TestController' end expect(RailsAdmin.config.parent_controller).to eq 'TestController' end end describe '.parent_controller=' do context 'if RailsAdmin::ApplicationController is already loaded' do before do # preload controllers (e.g. when config.eager_load = true) RailsAdmin::MainController end after do RailsAdmin::Config.reset RailsAdmin.send(:remove_const, :ApplicationController) load RailsAdmin::Engine.root.join('app/controllers/rails_admin/application_controller.rb') end it 'can be changed' do RailsAdmin.config.parent_controller = 'ApplicationController' expect(RailsAdmin::ApplicationController.superclass).to eq ApplicationController expect(RailsAdmin::MainController.superclass.superclass).to eq ApplicationController end end end describe '.forgery_protection_settings' do it 'uses with: :exception by default' do expect(RailsAdmin.config.forgery_protection_settings).to eq(with: :exception) end it 'allows to customize settings' do RailsAdmin.config do |config| config.forgery_protection_settings = {with: :null_session} end expect(RailsAdmin.config.forgery_protection_settings).to eq(with: :null_session) end end describe '.model' do let(:fields) { described_class.model(Team).fields } before do described_class.model Team do field :players do visible false end end end context 'when model expanded' do before do described_class.model(Team) do field :fans end end it 'execute all passed blocks' do expect(fields.map(&:name)).to match_array %i[players fans] end end context 'when expand redefine behavior' do before do described_class.model Team do field :players end end it 'execute all passed blocks' do expect(fields.find { |f| f.name == :players }.visible).to be true end end context 'when model has no table yet', active_record: true do it 'does not try to apply the configuration block' do described_class.model(WithoutTable) do include_all_fields end end end end describe '.reset' do before do RailsAdmin.config do |config| config.included_models = %w[Player Team] end RailsAdmin::AbstractModel.all RailsAdmin::Config.reset RailsAdmin.config do |config| config.excluded_models = ['Player'] end end subject { RailsAdmin::AbstractModel.all.map { |am| am.model.name } } it 'refreshes the result of RailsAdmin::AbstractModel.all' do expect(subject).not_to include 'Player' expect(subject).to include 'Team' end end describe '.reload!' do before do RailsAdmin.config Player do field :name end RailsAdmin.config Team do field :color, :integer end end it 'clears current configuration' do RailsAdmin::Config.reload! expect(RailsAdmin::Config.model(Player).fields.map(&:name)).to include :number end it 'reloads the configuration from the initializer' do RailsAdmin::Config.reload! expect(RailsAdmin::Config.model(Team).fields.find { |f| f.name == :color }.type).to eq :hidden end end end module ExampleModule class AuthorizationAdapter; end class ConfigurationAdapter; end class AuditingAdapter; end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/engine_spec.rb
spec/rails_admin/engine_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Engine do context 'on class unload' do let(:fields) { RailsAdmin.config(Player).edit.fields } before do Rails.application.config.cache_classes = false RailsAdmin.config(Player) do field :name field :number end end after { Rails.application.config.cache_classes = true } it 'triggers RailsAdmin config to be reloaded' do # this simulates rails code reloading RailsAdmin::Engine.initializers.find do |i| i.name == 'RailsAdmin reload config in development' end.block.call(Rails.application) Rails.application.executor.wrap do ActiveSupport::Reloader.new.tap(&:class_unload!).complete! end RailsAdmin.config(Player) do field :number end expect(fields.map(&:name)).to match_array %i[number] end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/install_generator_spec.rb
spec/rails_admin/install_generator_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'generators/rails_admin/install_generator' RSpec.describe RailsAdmin::InstallGenerator, type: :generator do destination File.expand_path('../dummy_app/tmp/generator', __dir__) arguments ['admin', "--asset=#{CI_ASSET}", '--force'] before do prepare_destination File.write(File.join(destination_root, 'package.json'), '{"license": "MIT"}') FileUtils.touch File.join(destination_root, 'Gemfile') FileUtils.mkdir_p(File.join(destination_root, 'config/initializers')) File.write(File.join(destination_root, 'config/routes.rb'), <<~RUBY) Rails.application.routes.draw do # empty end RUBY File.write(File.join(destination_root, 'Rakefile'), <<-RUBY.gsub(/^ {4}/, '')) desc 'Stub for testing' task 'css:install:sass' RUBY end after do FileUtils.rm_rf(destination_root) end it 'mounts RailsAdmin as Engine and generates RailsAdmin Initializer' do Dir.chdir(destination_root) do run_generator end expect(destination_root).to( have_structure do directory 'config' do directory 'initializers' do file 'rails_admin.rb' do contains 'RailsAdmin.config' contains 'asset_source =' end end file 'routes.rb' do contains "mount RailsAdmin::Engine => '/admin', as: 'rails_admin'" end end case CI_ASSET when :webpacker file 'app/javascript/packs/rails_admin.js' do contains 'import "rails_admin/src/rails_admin/base"' end file 'app/javascript/stylesheets/rails_admin.scss' do contains '@import "rails_admin/src/rails_admin/styles/base"' end when :sprockets file 'Gemfile' do contains 'sassc-rails' end when :importmap file 'app/javascript/rails_admin.js' do contains 'import "rails_admin/src/rails_admin/base"' end file 'app/assets/stylesheets/rails_admin.scss' do contains '$fa-font-path: ".";' contains '@import "rails_admin/src/rails_admin/styles/base"' end file 'config/importmap.rails_admin.rb' do contains 'pin "rails_admin", preload: true' contains 'pin "rails_admin/src/rails_admin/base", to: "https://ga.jspm.io/npm:rails_admin@' contains 'pin "bootstrap", to: "https://ga.jspm.io/npm:bootstrap@' end file 'config/initializers/assets.rb' do contains 'Rails.root.join("node_modules/@fortawesome/fontawesome-free/webfonts")' end file 'package.json' do contains 'sass ./app/assets/stylesheets/rails_admin.scss:./app/assets/builds/rails_admin.css' end when :webpack file 'app/javascript/rails_admin.js' do contains 'import "rails_admin/src/rails_admin/base"' end file 'app/assets/stylesheets/rails_admin.scss' do contains '$fa-font-path: ".";' contains '@import "rails_admin/src/rails_admin/styles/base"' end file 'package.json' do contains 'webpack --config webpack.config.js' contains 'sass ./app/assets/stylesheets/rails_admin.scss:./app/assets/builds/rails_admin.css' end when :vite file 'app/frontend/entrypoints/rails_admin.js' do contains 'import "~/stylesheets/rails_admin.scss"' contains 'import "rails_admin/src/rails_admin/base"' end file 'app/frontend/stylesheets/rails_admin.scss' do contains '$fa-font-path: "@fortawesome/fontawesome-free/webfonts";' contains '@import "rails_admin/src/rails_admin/styles/base"' end file 'package.json' do contains 'sass' end end end, ) end it 'inserts asset_source option to RailsAdmin Initializer' do File.write(File.join(destination_root, 'config/initializers/rails_admin.rb'), <<~RUBY) RailsAdmin.config do |config| # empty end RUBY Dir.chdir(destination_root) do run_generator end expect(File.read(File.join(destination_root, 'config/initializers/rails_admin.rb'))).to include 'config.asset_source =' end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/support/hash_helper_spec.rb
spec/rails_admin/support/hash_helper_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::HashHelper do let(:hash) do { 'subject' => 'Test', 'user' => { name: 'Dirk', 'title' => 'Holistic Detective', 'clients' => [ {name: 'Zaphod'}, {'name' => 'Arthur'}, ], }, } end describe 'symbolize' do let(:symbolized_hash) { RailsAdmin::HashHelper.symbolize(hash) } it 'symbolizes top-level hash keys' do %i[subject user].each do |key| expect(symbolized_hash.keys).to include(key) end end it 'symbolizes nested hashes' do %i[name title clients].each do |key| expect(symbolized_hash[:user].keys).to include(key) end end it 'symbolizes nested hashes inside of array values' do clients = symbolized_hash[:user][:clients] expect(clients.length).to eq(2) expect(clients[0][:name]).to eq(:Zaphod) expect(clients[1][:name]).to eq(:Arthur) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/support/datetime_spec.rb
spec/rails_admin/support/datetime_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Support::Datetime do describe '#to_flatpickr_format' do { '%D de %M de %Y, %H:%M:%S' => 'm/d/y \d\e i \d\e Y, H:i:S', '%d/%-m/%Y, %H:%M:%S' => 'd/n/Y, H:i:S', '%d de %B de %Y' => 'd \d\e F \d\e Y', '%-d %B %Y' => 'j F Y', '%F %T' => 'Y-m-d H:i:S', '%Y-%m-%dT%H:%M:%S%:z' => 'Y-m-d\TH:i:S+00:00', '%HH%MM%SS' => 'H\Hi\MS\S', 'a%-Ha%-Ma%-Sa%:za' => '\aH\ai\as\a+00:00\a', '%B %-d at %-l:%M %p' => 'F j \a\t h:i K', }.each do |strftime_format, flatpickr_format| it "convert strftime_format to flatpickr_format - example #{strftime_format}" do expect(RailsAdmin::Support::Datetime.to_flatpickr_format(strftime_format)).to eq flatpickr_format end end it 'raises an error with unsupported directive' do expect do RailsAdmin::Support::Datetime.to_flatpickr_format('%C') end.to raise_error(/Unsupported/) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/support/csv_converter_spec.rb
spec/rails_admin/support/csv_converter_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::CSVConverter do it 'keeps headers ordering' do RailsAdmin.config(Player) do export do field :number field :name end end FactoryBot.create :player objects = Player.all schema = {only: %i[number name]} expect(RailsAdmin::CSVConverter.new(objects, schema).to_csv({})[2]).to match(/Number,Name/) end describe '#generate_csv_header' do let(:objects) { FactoryBot.create_list :player, 1 } before do RailsAdmin.config(Player) do export do field :number field :name end end end it 'does not break when non-existent fields are given' do expect(RailsAdmin::CSVConverter.new(objects, {only: %i[name foo], include: {bar: :baz}}).send(:generate_csv_header)). to eq ['Name'] end it 'does not break when non-association fields are given to :include' do expect(RailsAdmin::CSVConverter.new(objects, {only: %i[name foo], include: {name: :name}}).send(:generate_csv_header)). to eq ['Name'] end end describe '#to_csv' do before do RailsAdmin.config(Player) do export do field :number field :name end end end let(:objects) { FactoryBot.create_list :player, 1, number: 1, name: 'なまえ' } let(:schema) { {only: %i[number name]} } let(:options) { {encoding_to: encoding} } subject { RailsAdmin::CSVConverter.new(objects, schema).to_csv(options) } context 'when encoding FROM latin1', active_record: true do let(:connection_config) do if ActiveRecord::Base.respond_to?(:connection_db_config) ActiveRecord::Base.connection_db_config.configuration_hash else ActiveRecord::Base.connection_config end end let(:encoding) { '' } let(:objects) { FactoryBot.create_list :player, 1, number: 1, name: 'Josè'.encode('ISO-8859-1') } before do case connection_config[:adapter] when 'postgresql' @connection = ActiveRecord::Base.connection.raw_connection @connection.set_client_encoding('latin1') when 'mysql2' ActiveRecord::Base.connection.execute('SET NAMES latin1;') end end after do case connection_config[:adapter] when 'postgresql' @connection.set_client_encoding('utf8') when 'mysql2' ActiveRecord::Base.connection.execute('SET NAMES utf8;') end end it 'exports to ISO-8859-1' do expect(subject[1]).to eq 'ISO-8859-1' expect(subject[2].encoding).to eq Encoding::ISO_8859_1 expect(subject[2].unpack1('H*')). to eq '4e756d6265722c4e616d650a312c4a6f73e80a' end end context 'when encoding to UTF-8' do let(:encoding) { 'UTF-8' } it 'exports to UTF-8 with BOM' do expect(subject[1]).to eq 'UTF-8' expect(subject[2].encoding).to eq Encoding::UTF_8 expect(subject[2].unpack1('H*')). to eq 'efbbbf4e756d6265722c4e616d650a312ce381aae381bee381880a' # have BOM end end context 'when encoding to Shift_JIS' do let(:encoding) { 'Shift_JIS' } it 'exports to Shift_JIS' do expect(subject[1]).to eq 'Shift_JIS' expect(subject[2].encoding).to eq Encoding::Shift_JIS expect(subject[2].unpack1('H*')). to eq '4e756d6265722c4e616d650a312c82c882dc82a60a' end end context 'when encoding to UTF-16(ASCII-incompatible)' do let(:encoding) { 'UTF-16' } it 'encodes to expected byte sequence' do expect(subject[1]).to eq 'UTF-16' expect(subject[2].encoding).to eq Encoding::UTF_16 expect(subject[2].unpack1('H*').force_encoding('US-ASCII')). to eq 'feff004e0075006d006200650072002c004e0061006d0065000a0031002c306a307e3048000a' end end context 'when specifying a column separator' do context 'when options keys are symbolized' do let(:options) { {encoding_to: 'UTF-8', generator: {col_sep: '___'}} } it 'uses the column separator specified' do expect(subject[2].unpack1('H*')). to eq 'efbbbf4e756d6265725f5f5f4e616d650a315f5f5fe381aae381bee381880a' end end context 'when options keys are string' do let(:options) { {'encoding_to' => 'UTF-8', 'generator' => {'col_sep' => '___'}} } it 'uses the column separator specified' do expect(subject[2].unpack1('H*')). to eq 'efbbbf4e756d6265725f5f5f4e616d650a315f5f5fe381aae381bee381880a' end end end context 'when objects is empty' do let(:objects) { [] } let(:options) { {} } it 'generates an empty csv' do expect(subject[2]).to eq("\n") end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/active_record_spec.rb
spec/rails_admin/adapters/active_record_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'timecop' RSpec.describe 'RailsAdmin::Adapters::ActiveRecord', active_record: true do let(:activerecord_config) do if ::ActiveRecord::Base.respond_to? :connection_db_config ::ActiveRecord::Base.connection_db_config.configuration_hash else ::ActiveRecord::Base.connection_config end end let(:like) do if %w[postgresql postgis].include? activerecord_config[:adapter] '(field ILIKE ?)' else '(LOWER(field) LIKE ?)' end end let(:not_like) do if %w[postgresql postgis].include? activerecord_config[:adapter] '(field NOT ILIKE ?)' else '(LOWER(field) NOT LIKE ?)' end end def predicates_for(scope) scope.where_clause.instance_variable_get(:@predicates) # .map do |predicate| # if predicate.is_a? Arel::Nodes::BoundSqlLiteral # binds = predicate.positional_binds # predicate.sql_with_placeholders.delete_prefix('(').delete_suffix(')').gsub('?') do |_| # bind = binds.shift # case bind # when Date # "'#{bind.to_fs(:db)}'" # when DateTime, Time # "'#{bind.to_fs(:db)}'" # else # p bind # bind.to_s # end # end # else # predicate # end # end end describe '#associations' do it 'returns Association class' do expect(RailsAdmin::AbstractModel.new(Player).associations.first). to be_a_kind_of RailsAdmin::Adapters::ActiveRecord::Association end end describe '#properties' do it 'returns Property class' do expect(RailsAdmin::AbstractModel.new(Player).properties.first). to be_a_kind_of RailsAdmin::Adapters::ActiveRecord::Property end end describe '#base_class' do it 'returns inheritance base class' do expect(RailsAdmin::AbstractModel.new(Hardball).base_class).to eq Ball end end describe 'data access methods' do let(:abstract_model) { RailsAdmin::AbstractModel.new('Player') } before do @players = FactoryBot.create_list(:player, 3) + [ # Multibyte players FactoryBot.create(:player, name: 'Антоха'), FactoryBot.create(:player, name: 'Петруха'), ] end it '#new returns an ActiveRecord instance' do expect(abstract_model.new).to be_a(ActiveRecord::Base) end it '#get returns an ActiveRecord instance' do expect(abstract_model.get(@players.first.id)).to eq(@players.first) end it '#get returns nil when id does not exist' do expect(abstract_model.get('abc')).to be_nil end it '#get returns an object that can be passed to ActiveJob' do expect { NullJob.perform_later(abstract_model.get(@players.first.id)) }.not_to raise_error end it '#first returns a player' do expect(@players).to include abstract_model.first end describe '#count' do it 'returns count of items' do expect(abstract_model.count).to eq(@players.count) end context 'when default-scoped with select' do before do class PlayerWithDefaultScope < Player self.table_name = 'players' default_scope { select(:id, :name) } end end let(:abstract_model) { RailsAdmin::AbstractModel.new('PlayerWithDefaultScope') } it 'does not break' do expect(abstract_model.count).to eq(@players.count) end end end it '#destroy destroys multiple items' do abstract_model.destroy(@players[0..1]) expect(Player.all).to match_array(@players[2..]) end it '#where returns filtered results' do expect(abstract_model.where(name: @players.first.name)).to eq([@players.first]) end describe '#all' do it 'works without options' do expect(abstract_model.all).to match_array @players end it 'supports eager loading' do expect(abstract_model.all(include: :team).includes_values).to eq([:team]) end it 'supports limiting' do expect(abstract_model.all(limit: 2).size).to eq(2) end it 'supports retrieval by bulk_ids' do expect(abstract_model.all(bulk_ids: @players[0..1].collect(&:id))).to match_array @players[0..1] end it 'supports retrieval by bulk_ids with composite primary keys', composite_primary_keys: true do expect(RailsAdmin::AbstractModel.new(Fanship).all( bulk_ids: %w[1_2 3_4], ).to_sql.tr('`', '"')).to include 'WHERE ("fans_teams"."fan_id" = 1 AND "fans_teams"."team_id" = 2 OR "fans_teams"."fan_id" = 3 AND "fans_teams"."team_id" = 4)' end it 'supports pagination' do expect(abstract_model.all(sort: 'id', page: 2, per: 1)).to eq(@players[-2, 1]) expect(abstract_model.all(sort: 'id', page: 1, per: 2)).to eq(@players[-2, 2].reverse) end it 'supports ordering' do expect(abstract_model.all(sort: 'id', sort_reverse: true)).to eq(@players.sort) expect(abstract_model.all(sort: %w[id name], sort_reverse: true).to_sql.tr('`', '"')).to include('ORDER BY "players"."id" ASC, "players"."name" ASC') expect(abstract_model.all(include: :team, sort: {players: :name, teams: :name}, sort_reverse: true).to_sql.tr('`', '"')).to include('ORDER BY "players"."name" ASC, "teams"."name" ASC') expect { abstract_model.all(sort: 1, sort_reverse: true) }.to raise_error ArgumentError, /Unsupported/ end it 'supports querying' do results = abstract_model.all(query: @players[1].name) expect(results).to eq(@players[1..1]) end it 'supports multibyte querying' do unless activerecord_config[:adapter] == 'sqlite3' results = abstract_model.all(query: @players[4].name) expect(results).to eq(@players[4, 1]) end end it 'supports filtering' do expect(abstract_model.all(filters: {'name' => {'0000' => {o: 'is', v: @players[1].name}}})).to eq(@players[1..1]) end end end describe '#query_scope' do let(:abstract_model) { RailsAdmin::AbstractModel.new('Team') } before do @teams = [{}, {name: 'somewhere foos'}, {manager: 'foo junior'}]. collect { |h| FactoryBot.create :team, h } end it 'makes correct query' do expect(abstract_model.all(query: 'foo')).to match_array @teams[1..2] end context "when field's searchable_columns is empty" do before do RailsAdmin.config do |c| c.model Team do field :players end end end it 'does not break' do expect { abstract_model.all(query: 'foo') }.not_to raise_error end end context 'when parsing is not idempotent' do before do RailsAdmin.config do |c| c.model Team do field :name do def parse_value(value) "#{value}s" end end end end end it 'parses value only once' do expect(abstract_model.all(query: 'foo')).to match_array @teams[1] end end end describe '#filter_scope' do let(:abstract_model) { RailsAdmin::AbstractModel.new('Team') } before do @division = FactoryBot.create :division, name: 'bar division' @teams = [{}, {division: @division}, {name: 'somewhere foos', division: @division}, {name: 'nowhere foos'}]. collect { |h| FactoryBot.create :team, h } end context 'without configuration' do before do allow(Rails.configuration).to receive(:database_configuration) { nil } end after do allow(Rails.configuration).to receive(:database_configuration).and_call_original end it 'does not raise error' do expect { abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'foo'}}}) }.to_not raise_error end end it 'makes correct query' do expect(abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'foo'}}, 'division' => {'0001' => {o: 'like', v: 'bar'}}}, include: :division)).to eq([@teams[2]]) end context 'when parsing is not idempotent' do before do RailsAdmin.config do |c| c.model Team do field :name do def parse_value(value) "some#{value}" end end end end end it 'parses value only once' do expect(abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'where'}}})).to match_array @teams[2] end end context 'when a default_search_operator is set' do before do RailsAdmin.config do |c| c.default_search_operator = 'starts_with' end end it 'only matches on prefix' do # Specified operator is honored and matches expect(abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'where'}}})).to match_array @teams[2..3] # No operator falls back to the default_search_operator(starts_with) and doesn't match NON-PREFIX expect(abstract_model.all(filters: {'name' => {'0000' => {v: 'where'}}})).to be_empty # No operator falls back to the default_search_operator(starts_with) and doesn't match NON-PREFIX expect(abstract_model.all(filters: {'name' => {'0000' => {v: 'somewhere'}}})).to match_array @teams[2] end end end describe '#build_statement' do let(:abstract_model) { RailsAdmin::AbstractModel.new('FieldTest') } def build_statement(type, value, operator) abstract_model.send(:build_statement, :field, type, value, operator) end it "ignores '_discard' operator or value" do [['_discard', ''], ['', '_discard']].each do |value, operator| expect(build_statement(:string, value, operator)).to be_nil end end describe 'string type queries' do it 'supports string type query' do expect(build_statement(:string, '', nil)).to be_nil expect(build_statement(:string, 'foo', 'was')).to be_nil expect(build_statement(:string, 'foo', 'default')).to eq([like, '%foo%']) expect(build_statement(:string, 'foo', 'like')).to eq([like, '%foo%']) expect(build_statement(:string, 'foo', 'not_like')).to eq([not_like, '%foo%']) expect(build_statement(:string, 'foo', 'starts_with')).to eq([like, 'foo%']) expect(build_statement(:string, 'foo', 'ends_with')).to eq([like, '%foo']) expect(build_statement(:string, 'foo', 'is')).to eq(['(field = ?)', 'foo']) end it 'performs case-insensitive searches' do unless %w[postgresql postgis].include?(activerecord_config[:adapter]) expect(build_statement(:string, 'foo', 'default')).to eq([like, '%foo%']) expect(build_statement(:string, 'FOO', 'default')).to eq([like, '%foo%']) end end it 'chooses like statement in per-model basis' do allow(FieldTest.connection).to receive(:adapter_name).and_return('postgresql') expect(build_statement(:string, 'foo', 'default')).to eq(['(field ILIKE ?)', '%foo%']) allow(FieldTest.connection).to receive(:adapter_name).and_return('sqlite3') expect(build_statement(:string, 'foo', 'default')).to eq(['(LOWER(field) LIKE ?)', '%foo%']) end it "supports '_blank' operator" do [['_blank', ''], ['', '_blank']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(["(field IS NULL OR field = '')"]) end end it "supports '_present' operator" do [['_present', ''], ['', '_present']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(["(field IS NOT NULL AND field != '')"]) end end it "supports '_null' operator" do [['_null', ''], ['', '_null']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_not_null' operator" do [['_not_null', ''], ['', '_not_null']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(['(field IS NOT NULL)']) end end it "supports '_empty' operator" do [['_empty', ''], ['', '_empty']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(["(field = '')"]) end end it "supports '_not_empty' operator" do [['_not_empty', ''], ['', '_not_empty']].each do |value, operator| expect(build_statement(:string, value, operator)).to eq(["(field != '')"]) end end end describe 'boolean type queries' do it 'supports boolean type query' do %w[false f 0].each do |value| expect(build_statement(:boolean, value, nil)).to eq(['(field IS NULL OR field = ?)', false]) end %w[true t 1].each do |value| expect(build_statement(:boolean, value, nil)).to eq(['(field = ?)', true]) end expect(build_statement(:boolean, 'word', nil)).to be_nil end it "supports '_blank' operator" do [['_blank', ''], ['', '_blank']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_present' operator" do [['_present', ''], ['', '_present']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NOT NULL)']) end end it "supports '_null' operator" do [['_null', ''], ['', '_null']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_not_null' operator" do [['_not_null', ''], ['', '_not_null']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NOT NULL)']) end end it "supports '_empty' operator" do [['_empty', ''], ['', '_empty']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_not_empty' operator" do [['_not_empty', ''], ['', '_not_empty']].each do |value, operator| expect(build_statement(:boolean, value, operator)).to eq(['(field IS NOT NULL)']) end end end describe 'numeric type queries' do it 'supports integer type query' do expect(build_statement(:integer, '1', nil)).to eq(['(field = ?)', 1]) expect(build_statement(:integer, 'word', nil)).to be_nil expect(build_statement(:integer, '1', 'default')).to eq(['(field = ?)', 1]) expect(build_statement(:integer, 'word', 'default')).to be_nil expect(build_statement(:integer, '1', 'between')).to eq(['(field = ?)', 1]) expect(build_statement(:integer, 'word', 'between')).to be_nil expect(build_statement(:integer, ['6', '', ''], 'default')).to eq(['(field = ?)', 6]) expect(build_statement(:integer, ['7', '10', ''], 'default')).to eq(['(field = ?)', 7]) expect(build_statement(:integer, ['8', '', '20'], 'default')).to eq(['(field = ?)', 8]) expect(build_statement(:integer, %w[9 10 20], 'default')).to eq(['(field = ?)', 9]) end it 'supports integer type range query' do expect(build_statement(:integer, ['', '', ''], 'between')).to be_nil expect(build_statement(:integer, ['2', '', ''], 'between')).to be_nil expect(build_statement(:integer, ['', '3', ''], 'between')).to eq(['(field >= ?)', 3]) expect(build_statement(:integer, ['', '', '5'], 'between')).to eq(['(field <= ?)', 5]) expect(build_statement(:integer, ['', '10', '20'], 'between')).to eq(['(field BETWEEN ? AND ?)', 10, 20]) expect(build_statement(:integer, %w[15 10 20], 'between')).to eq(['(field BETWEEN ? AND ?)', 10, 20]) expect(build_statement(:integer, ['', 'word1', ''], 'between')).to be_nil expect(build_statement(:integer, ['', '', 'word2'], 'between')).to be_nil expect(build_statement(:integer, ['', 'word3', 'word4'], 'between')).to be_nil end it 'supports both decimal and float type queries' do expect(build_statement(:decimal, '1.1', nil)).to eq(['(field = ?)', 1.1]) expect(build_statement(:decimal, 'word', nil)).to be_nil expect(build_statement(:decimal, '1.1', 'default')).to eq(['(field = ?)', 1.1]) expect(build_statement(:decimal, 'word', 'default')).to be_nil expect(build_statement(:decimal, '1.1', 'between')).to eq(['(field = ?)', 1.1]) expect(build_statement(:decimal, 'word', 'between')).to be_nil expect(build_statement(:decimal, ['6.1', '', ''], 'default')).to eq(['(field = ?)', 6.1]) expect(build_statement(:decimal, ['7.1', '10.1', ''], 'default')).to eq(['(field = ?)', 7.1]) expect(build_statement(:decimal, ['8.1', '', '20.1'], 'default')).to eq(['(field = ?)', 8.1]) expect(build_statement(:decimal, ['9.1', '10.1', '20.1'], 'default')).to eq(['(field = ?)', 9.1]) expect(build_statement(:decimal, ['', '', ''], 'between')).to be_nil expect(build_statement(:decimal, ['2.1', '', ''], 'between')).to be_nil expect(build_statement(:decimal, ['', '3.1', ''], 'between')).to eq(['(field >= ?)', 3.1]) expect(build_statement(:decimal, ['', '', '5.1'], 'between')).to eq(['(field <= ?)', 5.1]) expect(build_statement(:decimal, ['', '10.1', '20.1'], 'between')).to eq(['(field BETWEEN ? AND ?)', 10.1, 20.1]) expect(build_statement(:decimal, ['15.1', '10.1', '20.1'], 'between')).to eq(['(field BETWEEN ? AND ?)', 10.1, 20.1]) expect(build_statement(:decimal, ['', 'word1', ''], 'between')).to be_nil expect(build_statement(:decimal, ['', '', 'word2'], 'between')).to be_nil expect(build_statement(:decimal, ['', 'word3', 'word4'], 'between')).to be_nil expect(build_statement(:float, '1.1', nil)).to eq(['(field = ?)', 1.1]) expect(build_statement(:float, 'word', nil)).to be_nil expect(build_statement(:float, '1.1', 'default')).to eq(['(field = ?)', 1.1]) expect(build_statement(:float, 'word', 'default')).to be_nil expect(build_statement(:float, '1.1', 'between')).to eq(['(field = ?)', 1.1]) expect(build_statement(:float, 'word', 'between')).to be_nil expect(build_statement(:float, ['6.1', '', ''], 'default')).to eq(['(field = ?)', 6.1]) expect(build_statement(:float, ['7.1', '10.1', ''], 'default')).to eq(['(field = ?)', 7.1]) expect(build_statement(:float, ['8.1', '', '20.1'], 'default')).to eq(['(field = ?)', 8.1]) expect(build_statement(:float, ['9.1', '10.1', '20.1'], 'default')).to eq(['(field = ?)', 9.1]) expect(build_statement(:float, ['', '', ''], 'between')).to be_nil expect(build_statement(:float, ['2.1', '', ''], 'between')).to be_nil expect(build_statement(:float, ['', '3.1', ''], 'between')).to eq(['(field >= ?)', 3.1]) expect(build_statement(:float, ['', '', '5.1'], 'between')).to eq(['(field <= ?)', 5.1]) expect(build_statement(:float, ['', '10.1', '20.1'], 'between')).to eq(['(field BETWEEN ? AND ?)', 10.1, 20.1]) expect(build_statement(:float, ['15.1', '10.1', '20.1'], 'between')).to eq(['(field BETWEEN ? AND ?)', 10.1, 20.1]) expect(build_statement(:float, ['', 'word1', ''], 'between')).to be_nil expect(build_statement(:float, ['', '', 'word2'], 'between')).to be_nil expect(build_statement(:float, ['', 'word3', 'word4'], 'between')).to be_nil end it "supports '_blank' operator" do [['_blank', ''], ['', '_blank']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NULL)']) end end end it "supports '_present' operator" do [['_present', ''], ['', '_present']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NOT NULL)']) end end end it "supports '_null' operator" do [['_null', ''], ['', '_null']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NULL)']) end end end it "supports '_not_null' operator" do [['_not_null', ''], ['', '_not_null']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NOT NULL)']) end end end it "supports '_empty' operator" do [['_empty', ''], ['', '_empty']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NULL)']) end end end it "supports '_not_empty' operator" do [['_not_empty', ''], ['', '_not_empty']].each do |value, operator| aggregate_failures do expect(build_statement(:integer, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:decimal, value, operator)).to eq(['(field IS NOT NULL)']) expect(build_statement(:float, value, operator)).to eq(['(field IS NOT NULL)']) end end end end describe 'date/time type queries' do let(:scope) { FieldTest.all } it 'supports date type query' do expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: ['', '2012-02-01', '2012-03-01'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.date_field BETWEEN ? AND ?)', Date.new(2012, 2, 1), Date.new(2012, 3, 1)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: ['', '2012-03-01', ''], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.date_field >= ?)', Date.new(2012, 3, 1)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: ['', '', '2012-02-01'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.date_field <= ?)', Date.new(2012, 2, 1)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: ['2012-02-01'], o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.date_field = ?)', Date.new(2012, 2, 1)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: [], o: 'today'}}))).to eq(predicates_for(scope.where('(field_tests.date_field = ?)', Date.today))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: [], o: 'yesterday'}}))).to eq(predicates_for(scope.where('(field_tests.date_field = ?)', Date.yesterday))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: [], o: 'this_week'}}))).to eq(predicates_for(scope.where('(field_tests.date_field BETWEEN ? AND ?)', Date.today.beginning_of_week, Date.today.end_of_week))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'date_field' => {'1' => {v: [], o: 'last_week'}}))).to eq(predicates_for(scope.where('(field_tests.date_field BETWEEN ? AND ?)', 1.week.ago.to_date.beginning_of_week, 1.week.ago.to_date.end_of_week))) end it 'supports datetime type query' do expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: ['', '2012-02-01T12:00:00', '2012-03-01T12:00:00'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field BETWEEN ? AND ?)', Time.utc(2012, 2, 1, 12), Time.utc(2012, 3, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: ['', '2012-03-01T12:00:00', ''], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field >= ?)', Time.utc(2012, 3, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: ['', '', '2012-02-01T12:00:00'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field <= ?)', Time.utc(2012, 2, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: ['2012-02-01T12:00:00'], o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field = ?)', Time.utc(2012, 2, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: [], o: 'today'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field BETWEEN ? AND ?)', Date.today.beginning_of_day, Date.today.end_of_day))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: [], o: 'yesterday'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field BETWEEN ? AND ?)', Date.yesterday.beginning_of_day, Date.yesterday.end_of_day))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: [], o: 'this_week'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field BETWEEN ? AND ?)', Date.today.beginning_of_week.beginning_of_day, Date.today.end_of_week.end_of_day))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'datetime_field' => {'1' => {v: [], o: 'last_week'}}))).to eq(predicates_for(scope.where('(field_tests.datetime_field BETWEEN ? AND ?)', 1.week.ago.beginning_of_week, 1.week.ago.end_of_week))) end it 'supports time type query' do expect(predicates_for(abstract_model.send(:filter_scope, scope, 'time_field' => {'1' => {v: ['', '2000-01-01T12:00:00', '2000-01-01T14:00:00'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.time_field BETWEEN ? AND ?)', Time.utc(2000, 1, 1, 12), Time.utc(2000, 1, 1, 14)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'time_field' => {'1' => {v: ['', '2000-01-01T14:00:00', ''], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.time_field >= ?)', Time.utc(2000, 1, 1, 14)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'time_field' => {'1' => {v: ['', '', '2000-01-01T12:00:00'], o: 'between'}}))).to eq(predicates_for(scope.where('(field_tests.time_field <= ?)', Time.utc(2000, 1, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'time_field' => {'1' => {v: ['2000-01-01T12:00:00'], o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.time_field = ?)', Time.utc(2000, 1, 1, 12)))) expect(predicates_for(abstract_model.send(:filter_scope, scope, 'time_field' => {'1' => {v: ['2021-02-03T12:00:00'], o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.time_field = ?)', Time.utc(2000, 1, 1, 12)))) end end it 'supports enum type query' do expect(build_statement(:enum, '1', nil)).to eq(['(field IN (?))', ['1']]) end describe 'with ActiveRecord native enum' do let(:scope) { FieldTest.all } it 'supports integer enum type query' do expect(predicates_for(abstract_model.send(:filter_scope, scope, 'integer_enum_field' => {'1' => {v: 2, o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.integer_enum_field IN (?))', [2]))) end it 'supports string enum type query' do expect(predicates_for(abstract_model.send(:filter_scope, scope, 'string_enum_field' => {'1' => {v: 'm', o: 'default'}}))).to eq(predicates_for(scope.where('(field_tests.string_enum_field IN (?))', ['m']))) end end describe 'uuid type queries' do it 'supports uuid type query' do uuid = SecureRandom.uuid expect(build_statement(:uuid, uuid, nil)).to eq(['(field = ?)', uuid]) end it "supports '_blank' operator" do [['_blank', ''], ['', '_blank']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_present' operator" do [['_present', ''], ['', '_present']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NOT NULL)']) end end it "supports '_null' operator" do [['_null', ''], ['', '_null']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_not_null' operator" do [['_not_null', ''], ['', '_not_null']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NOT NULL)']) end end it "supports '_empty' operator" do [['_empty', ''], ['', '_empty']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NULL)']) end end it "supports '_not_empty' operator" do [['_not_empty', ''], ['', '_not_empty']].each do |value, operator| expect(build_statement(:uuid, value, operator)).to eq(['(field IS NOT NULL)']) end end end end describe 'model attribute method' do let(:abstract_model) { RailsAdmin::AbstractModel.new('Player') } it '#scoped returns relation object' do expect(abstract_model.scoped).to be_a_kind_of(ActiveRecord::Relation) end it '#table_name works' do expect(abstract_model.table_name).to eq('players') end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/mongoid_spec.rb
spec/rails_admin/adapters/mongoid_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::Adapters::Mongoid', mongoid: true do describe '#associations' do it 'returns Association class' do expect(RailsAdmin::AbstractModel.new(Player).associations.first). to be_a_kind_of RailsAdmin::Adapters::Mongoid::Association end end describe '#properties' do it 'returns Property class' do expect(RailsAdmin::AbstractModel.new(Player).properties.first). to be_a_kind_of RailsAdmin::Adapters::Mongoid::Property end end describe '#base_class' do it 'returns inheritance base class' do expect(RailsAdmin::AbstractModel.new(Hardball).base_class).to eq Ball end end describe 'data access methods' do before do @players = FactoryBot.create_list(:player, 3) @abstract_model = RailsAdmin::AbstractModel.new('Player') end it '#new returns a Mongoid::Document instance' do expect(@abstract_model.new).to be_a(Mongoid::Document) end it '#get returns a Mongoid::Document instance' do expect(@abstract_model.get(@players.first.id.to_s)).to eq(@players.first) end it '#get returns nil when id does not exist' do expect(@abstract_model.get('4f4f0824dcf2315093000000')).to be_nil end context 'when Mongoid.raise_not_found_error is false' do before { allow(Mongoid).to receive(:raise_not_found_error).and_return(false) } it '#get returns nil when id does not exist' do expect(@abstract_model.get('4f4f0824dcf2315093000000')).to be_nil end end it '#first returns a player' do expect(@players).to include @abstract_model.first end it '#count returns count of items' do expect(@abstract_model.count).to eq(@players.count) end it '#destroy destroys multiple items' do @abstract_model.destroy(@players[0..1]) expect(Player.all).to eq(@players[2..2]) end it '#where returns filtered results' do expect(@abstract_model.where(name: @players.first.name).to_a).to eq([@players.first]) end describe '#all' do it 'works without options' do expect(@abstract_model.all.to_a).to match_array @players end it 'supports eager loading' do expect(@abstract_model.all(include: :team).inclusions.collect(&:class_name)).to eq(['Team']) end it 'supports limiting' do expect(@abstract_model.all(limit: 2).to_a.size).to eq(2) end it 'supports retrieval by bulk_ids' do expect(@abstract_model.all(bulk_ids: @players[0..1].collect { |player| player.id.to_s }).to_a).to match_array @players[0..1] end it 'supports pagination' do expect(@abstract_model.all(sort: 'players._id', page: 2, per: 1).to_a).to eq(@players.sort_by(&:_id)[1..1]) # To prevent RSpec matcher to call Mongoid::Criteria#== method, # (we want to test equality of query result, not of Mongoid criteria) # to_a is added to invoke Mongoid query end it 'supports ordering' do expect(@abstract_model.all(sort: 'players._id', sort_reverse: true).to_a).to eq(@players.sort) expect(@abstract_model.all(sort: 'players._id', sort_reverse: false).to_a).to eq(@players.sort.reverse) end it 'supports querying' do expect(@abstract_model.all(query: @players[1].name)).to eq(@players[1..1]) end it 'supports filtering' do expect(@abstract_model.all(filters: {'name' => {'0000' => {o: 'is', v: @players[1].name}}})).to eq(@players[1..1]) end it 'ignores non-existent field name on filtering' do expect { @abstract_model.all(filters: {'dummy' => {'0000' => {o: 'is', v: @players[1].name}}}) }.not_to raise_error end end end describe 'searching on association' do describe 'whose type is belongs_to' do before do RailsAdmin.config Player do field :team do queryable true end end @players = FactoryBot.create_list(:player, 3) @team = FactoryBot.create :team, name: 'foobar' @team.players << @players[1] @abstract_model = RailsAdmin::AbstractModel.new('Player') end it 'supports querying' do expect(@abstract_model.all(query: 'foobar').to_a).to eq(@players[1..1]) end it 'supports filtering' do expect(@abstract_model.all(filters: {'team' => {'0000' => {o: 'is', v: 'foobar'}}}).to_a).to eq(@players[1..1]) end end describe 'whose type is has_many' do before do RailsAdmin.config Team do field :players do queryable true searchable :name end end @teams = FactoryBot.create_list(:team, 3) @players = [{team: @teams[1]}, {team: @teams[1], name: 'foobar'}, {team: @teams[2]}].collect { |h| FactoryBot.create :player, h } @abstract_model = RailsAdmin::AbstractModel.new('Team') end it 'supports querying' do expect(@abstract_model.all(query: 'foobar').to_a).to eq(@teams[1..1]) end it 'supports filtering' do expect(@abstract_model.all(filters: {'players' => {'0000' => {o: 'is', v: 'foobar'}}}).to_a).to eq(@teams[1..1]) end end describe 'whose type is has_and_belongs_to_many' do before do RailsAdmin.config Team do field :fans do queryable true searchable :name end end @teams = FactoryBot.create_list(:team, 3) @fans = [{}, {name: 'foobar'}, {}].collect { |h| FactoryBot.create :fan, h } @teams[1].fans = [@fans[0], @fans[1]] @teams[2].fans << @fans[2] @abstract_model = RailsAdmin::AbstractModel.new('Team') end it 'supports querying' do expect(@abstract_model.all(query: 'foobar').to_a).to eq(@teams[1..1]) end it 'supports filtering' do expect(@abstract_model.all(filters: {'fans' => {'0000' => {o: 'is', v: 'foobar'}}}).to_a).to eq(@teams[1..1]) end end describe 'whose type is embedded has_many' do before do RailsAdmin.config FieldTest do field :embeds do queryable true searchable :all end end @field_tests = FactoryBot.create_list(:field_test, 3) @field_tests[0].embeds.create name: 'foo' @field_tests[1].embeds.create name: 'bar' @abstract_model = RailsAdmin::AbstractModel.new('FieldTest') end it 'supports querying' do expect(@abstract_model.all(query: 'bar').to_a).to eq(@field_tests[1..1]) end it 'supports filtering' do expect(@abstract_model.all(filters: {'embeds' => {'0000' => {o: 'is', v: 'bar'}}}).to_a).to eq(@field_tests[1..1]) end end end describe '#query_scope' do before do @abstract_model = RailsAdmin::AbstractModel.new('Player') @players = [{}, {name: 'Many foos'}, {position: 'foo shortage'}]. collect { |h| FactoryBot.create :player, h } end it 'makes correct query' do expect(@abstract_model.all(query: 'foo').to_a).to match_array @players[1..2] end context 'when parsing is not idempotent' do before do RailsAdmin.config do |c| c.model Player do field :name do def parse_value(value) "#{value}s" end end end end end it 'parses value only once' do expect(@abstract_model.all(query: 'foo')).to match_array @players[1..1] end end end describe '#filter_scope' do before do @abstract_model = RailsAdmin::AbstractModel.new('Player') @team = FactoryBot.create :team, name: 'king of bar' @players = [{}, {team: @team}, {name: 'Many foos', team: @team}, {name: 'Great foo'}]. collect { |h| FactoryBot.create :player, h } end it 'makes correct query' do expect(@abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'foo'}}, 'team' => {'0001' => {o: 'like', v: 'bar'}}})).to eq([@players[2]]) end context 'when parsing is not idempotent' do before do RailsAdmin.config do |c| c.model Player do field :name do def parse_value(value) "#{value}s" end end end end end it 'parses value only once' do expect(@abstract_model.all(filters: {'name' => {'0000' => {o: 'like', v: 'foo'}}})).to match_array @players[2] end end end describe '#build_statement' do before do I18n.locale = :en @abstract_model = RailsAdmin::AbstractModel.new('FieldTest') end it "ignores '_discard' operator or value" do [['_discard', ''], ['', '_discard']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to be_nil end end it "supports '_blank' operator" do [['_blank', ''], ['', '_blank']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: {'$in' => [nil, '']}) end end it "supports '_present' operator" do [['_present', ''], ['', '_present']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: {'$nin' => [nil, '']}) end end it "supports '_null' operator" do [['_null', ''], ['', '_null']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: nil) end end it "supports '_not_null' operator" do [['_not_null', ''], ['', '_not_null']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: {'$ne' => nil}) end end it "supports '_empty' operator" do [['_empty', ''], ['', '_empty']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: '') end end it "supports '_not_empty' operator" do [['_not_empty', ''], ['', '_not_empty']].each do |value, operator| expect(@abstract_model.send(:build_statement, :name, :string, value, operator)).to eq(name: {'$ne' => ''}) end end it 'supports boolean type query' do %w[false f 0].each do |value| expect(@abstract_model.send(:build_statement, :field, :boolean, value, nil)).to eq(field: false) end %w[true t 1].each do |value| expect(@abstract_model.send(:build_statement, :field, :boolean, value, nil)).to eq(field: true) end expect(@abstract_model.send(:build_statement, :field, :boolean, 'word', nil)).to be_nil end it 'supports integer type query' do expect(@abstract_model.send(:build_statement, :field, :integer, '1', nil)).to eq(field: 1) expect(@abstract_model.send(:build_statement, :field, :integer, 'word', nil)).to be_nil end it 'supports integer type range query' do expect(@abstract_model.send(:build_statement, :field, :integer, ['', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :integer, ['2', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :integer, ['', '3', ''], 'between')).to eq(field: {'$gte' => 3}) expect(@abstract_model.send(:build_statement, :field, :integer, ['', '', '5'], 'between')).to eq(field: {'$lte' => 5}) expect(@abstract_model.send(:build_statement, :field, :integer, ['', '10', '20'], 'between')).to eq(field: {'$gte' => 10, '$lte' => 20}) expect(@abstract_model.send(:build_statement, :field, :integer, %w[15 10 20], 'between')).to eq(field: {'$gte' => 10, '$lte' => 20}) expect(@abstract_model.send(:build_statement, :field, :integer, ['', 'word1', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :integer, ['', '', 'word2'], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :integer, ['', 'word3', 'word4'], 'between')).to be_nil end it 'supports both decimal and float type queries' do expect(@abstract_model.send(:build_statement, :field, :decimal, '1.1', nil)).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :decimal, 'word', nil)).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, '1.1', 'default')).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :decimal, 'word', 'default')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, '1.1', 'between')).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :decimal, 'word', 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, ['6.1', '', ''], 'default')).to eq(field: 6.1) expect(@abstract_model.send(:build_statement, :field, :decimal, ['7.1', '10.1', ''], 'default')).to eq(field: 7.1) expect(@abstract_model.send(:build_statement, :field, :decimal, ['8.1', '', '20.1'], 'default')).to eq(field: 8.1) expect(@abstract_model.send(:build_statement, :field, :decimal, ['9.1', '10.1', '20.1'], 'default')).to eq(field: 9.1) expect(@abstract_model.send(:build_statement, :field, :decimal, ['', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, ['2.1', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, ['', '3.1', ''], 'between')).to eq(field: {'$gte' => 3.1}) expect(@abstract_model.send(:build_statement, :field, :decimal, ['', '', '5.1'], 'between')).to eq(field: {'$lte' => 5.1}) expect(@abstract_model.send(:build_statement, :field, :decimal, ['', '10.1', '20.1'], 'between')).to eq(field: {'$gte' => 10.1, '$lte' => 20.1}) expect(@abstract_model.send(:build_statement, :field, :decimal, ['15.1', '10.1', '20.1'], 'between')).to eq(field: {'$gte' => 10.1, '$lte' => 20.1}) expect(@abstract_model.send(:build_statement, :field, :decimal, ['', 'word1', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, ['', '', 'word2'], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :decimal, ['', 'word3', 'word4'], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, '1.1', nil)).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :float, 'word', nil)).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, '1.1', 'default')).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :float, 'word', 'default')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, '1.1', 'between')).to eq(field: 1.1) expect(@abstract_model.send(:build_statement, :field, :float, 'word', 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, ['6.1', '', ''], 'default')).to eq(field: 6.1) expect(@abstract_model.send(:build_statement, :field, :float, ['7.1', '10.1', ''], 'default')).to eq(field: 7.1) expect(@abstract_model.send(:build_statement, :field, :float, ['8.1', '', '20.1'], 'default')).to eq(field: 8.1) expect(@abstract_model.send(:build_statement, :field, :float, ['9.1', '10.1', '20.1'], 'default')).to eq(field: 9.1) expect(@abstract_model.send(:build_statement, :field, :float, ['', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, ['2.1', '', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, ['', '3.1', ''], 'between')).to eq(field: {'$gte' => 3.1}) expect(@abstract_model.send(:build_statement, :field, :float, ['', '', '5.1'], 'between')).to eq(field: {'$lte' => 5.1}) expect(@abstract_model.send(:build_statement, :field, :float, ['', '10.1', '20.1'], 'between')).to eq(field: {'$gte' => 10.1, '$lte' => 20.1}) expect(@abstract_model.send(:build_statement, :field, :float, ['15.1', '10.1', '20.1'], 'between')).to eq(field: {'$gte' => 10.1, '$lte' => 20.1}) expect(@abstract_model.send(:build_statement, :field, :float, ['', 'word1', ''], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, ['', '', 'word2'], 'between')).to be_nil expect(@abstract_model.send(:build_statement, :field, :float, ['', 'word3', 'word4'], 'between')).to be_nil end it 'supports string type query' do expect(@abstract_model.send(:build_statement, :field, :string, '', nil)).to be_nil expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'was')).to be_nil expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'default')).to eq(field: /foo/i) expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'like')).to eq(field: /foo/i) expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'not_like')).to eq(field: /^((?!foo).)*$/i) expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'starts_with')).to eq(field: /^foo/i) expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'ends_with')).to eq(field: /foo$/i) expect(@abstract_model.send(:build_statement, :field, :string, 'foo', 'is')).to eq(field: 'foo') end it 'supports date type query' do expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: ['', '2012-01-02', '2012-01-03'], o: 'between'}}).selector).to eq('$and' => [{'date_field' => {'$gte' => Date.new(2012, 1, 2), '$lte' => Date.new(2012, 1, 3)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: ['', '2012-01-03', ''], o: 'between'}}).selector).to eq('$and' => [{'date_field' => {'$gte' => Date.new(2012, 1, 3)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: ['', '', '2012-01-02'], o: 'between'}}).selector).to eq('$and' => [{'date_field' => {'$lte' => Date.new(2012, 1, 2)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: ['2012-01-02'], o: 'default'}}).selector).to eq('$and' => [{'date_field' => Date.new(2012, 1, 2)}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: [], o: 'today'}}).selector).to eq('$and' => [{'date_field' => Date.today}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: [], o: 'yesterday'}}).selector).to eq('$and' => [{'date_field' => Date.yesterday}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: [], o: 'this_week'}}).selector).to eq('$and' => [{'date_field' => {'$gte' => Date.today.beginning_of_week, '$lte' => Date.today.end_of_week}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'date_field' => {'1' => {v: [], o: 'last_week'}}).selector).to eq('$and' => [{'date_field' => {'$gte' => 1.week.ago.to_date.beginning_of_week, '$lte' => 1.week.ago.to_date.end_of_week}}]) end it 'supports datetime type query' do expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: ['', '2012-01-02T12:00:00', '2012-01-03T12:00:00'], o: 'between'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => Time.zone.local(2012, 1, 2, 12), '$lte' => Time.zone.local(2012, 1, 3, 12)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: ['', '2012-01-03T12:00:00', ''], o: 'between'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => Time.zone.local(2012, 1, 3, 12)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: ['', '', '2012-01-02T12:00:00'], o: 'between'}}).selector).to eq('$and' => [{'datetime_field' => {'$lte' => Time.zone.local(2012, 1, 2, 12)}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: ['2012-01-02T12:00:00'], o: 'default'}}).selector).to eq('$and' => [{'datetime_field' => Time.zone.local(2012, 1, 2, 12)}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: [], o: 'today'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => Date.today.beginning_of_day, '$lte' => Date.today.end_of_day}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: [], o: 'yesterday'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => Date.yesterday.beginning_of_day, '$lte' => Date.yesterday.end_of_day}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: [], o: 'this_week'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => Date.today.beginning_of_week.beginning_of_day, '$lte' => Date.today.end_of_week.end_of_day}}]) expect(@abstract_model.send(:filter_scope, FieldTest, 'datetime_field' => {'1' => {v: [], o: 'last_week'}}).selector).to eq('$and' => [{'datetime_field' => {'$gte' => 1.week.ago.to_date.beginning_of_week.beginning_of_day, '$lte' => 1.week.ago.to_date.end_of_week.end_of_day}}]) end it 'supports enum type query' do expect(@abstract_model.send(:build_statement, :field, :enum, '1', nil)).to eq(field: {'$in' => ['1']}) end end describe 'model attribute method' do before do @abstract_model = RailsAdmin::AbstractModel.new('Player') end it '#scoped returns relation object' do expect(@abstract_model.scoped).to be_instance_of(Mongoid::Criteria) end it '#table_name works' do expect(@abstract_model.table_name).to eq('players') end end describe 'serialization' do before do @abstract_model = RailsAdmin::AbstractModel.new('FieldTest') @controller = RailsAdmin::MainController.new end it 'accepts array value' do params = HashWithIndifferentAccess.new(array_field: '[1, 3]') @controller.send(:sanitize_params_for!, 'create', @abstract_model.config, params) expect(params[:array_field]).to eq([1, 3]) end it 'accepts hash value' do params = HashWithIndifferentAccess.new(hash_field: '{a: 1, b: 3}') @controller.send(:sanitize_params_for!, 'create', @abstract_model.config, params) expect(params[:hash_field]).to eq('a' => 1, 'b' => 3) end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/mongoid/object_extension_spec.rb
spec/rails_admin/adapters/mongoid/object_extension_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::Adapters::Mongoid::ObjectExtension', mongoid: true do describe 'has_many association' do let(:players) { FactoryBot.create_list :player, 2 } before do class TeamWithAutoSave < Team has_many :players, inverse_of: :team, autosave: true end end context 'on create' do before do team.player_ids = players.collect(&:id) team.players.each { |player| expect(player).to receive(:save).once.and_call_original } team.save end context 'with autosave: false' do let(:team) { FactoryBot.build(:team).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on save' do expect(team.reload.players).to match_array players end end context 'with autosave: true' do let(:team) { TeamWithAutoSave.new(FactoryBot.attributes_for(:team)).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on save' do expect(team.reload.players).to match_array players end end end context 'on update' do let(:team) { FactoryBot.create(:team).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } before do team.player_ids = players.collect(&:id) end context 'with autosave: false' do let(:team) { FactoryBot.create(:team).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on assignment' do expect(team.reload.players).to match_array players end end context 'with autosave: true' do let(:team) { TeamWithAutoSave.create(FactoryBot.attributes_for(:team)).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on assignment' do expect(team.reload.players).to match_array players end end end end describe 'has_one association' do let(:draft) { FactoryBot.create(:draft) } before do class PlayerWithAutoSave < Player has_one :draft, inverse_of: :player, autosave: true end end context 'on create' do before do player.draft = draft expect(player.draft._target).to receive(:save).once.and_call_original player.save end context 'with autosave: false' do let(:player) { FactoryBot.build(:player).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on save' do expect(player.reload.draft).to eq draft end end context 'with autosave: true' do let(:player) { PlayerWithAutoSave.new(FactoryBot.attributes_for(:player)).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on save' do expect(player.reload.draft).to eq draft end end end context 'on update' do before do player.draft = draft end context 'with autosave: false' do let(:player) { FactoryBot.create(:player).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on assignment' do expect(player.reload.draft).to eq draft end end context 'with autosave: true' do let(:player) { PlayerWithAutoSave.create(FactoryBot.attributes_for(:player)).extend(RailsAdmin::Adapters::Mongoid::ObjectExtension) } it 'persists associated documents changes on assignment' do expect(player.reload.draft).to eq draft end end end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/mongoid/association_spec.rb
spec/rails_admin/adapters/mongoid/association_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::Adapters::Mongoid::Association', mongoid: true do before :all do RailsAdmin::AbstractModel.reset_polymorphic_parents class MongoBlog include Mongoid::Document has_many :mongo_posts has_many :mongo_comments, as: :commentable belongs_to :librarian, polymorphic: true field :mongo_blog_id end class MongoPost include Mongoid::Document belongs_to :mongo_blog has_and_belongs_to_many :mongo_categories has_many :mongo_comments, as: :commentable embeds_one :mongo_note accepts_nested_attributes_for :mongo_note end class MongoCategory include Mongoid::Document has_and_belongs_to_many :mongo_posts belongs_to :librarian, polymorphic: true end class MongoUser include Mongoid::Document has_one :mongo_profile has_many :mongo_categories, as: :librarian embeds_many :mongo_notes accepts_nested_attributes_for :mongo_notes field :name, type: String field :message, type: String field :short_text, type: String validates :short_text, length: {maximum: 255} end class MongoProfile include Mongoid::Document belongs_to :mongo_user has_many :mongo_blogs, as: :librarian end class MongoComment include Mongoid::Document belongs_to :commentable, polymorphic: true end class MongoNote include Mongoid::Document embedded_in :mongo_post embedded_in :mongo_user end @blog = RailsAdmin::AbstractModel.new MongoBlog @post = RailsAdmin::AbstractModel.new MongoPost @category = RailsAdmin::AbstractModel.new MongoCategory @user = RailsAdmin::AbstractModel.new MongoUser @profile = RailsAdmin::AbstractModel.new MongoProfile @comment = RailsAdmin::AbstractModel.new MongoComment end after :all do RailsAdmin::AbstractModel.reset_polymorphic_parents end it 'lists associations' do expect(@post.associations.collect { |a| a.name.to_sym }).to match_array %i[mongo_blog mongo_categories mongo_comments mongo_note] end it 'reads correct and know types in [:belongs_to, :has_and_belongs_to_many, :has_many, :has_one]' do expect((@post.associations + @blog.associations + @user.associations).collect { |a| a.type.to_s }.uniq).to match_array %w[belongs_to has_and_belongs_to_many has_many has_one] end describe 'belongs_to association' do subject { @post.associations.detect { |a| a.name == :mongo_blog } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo blog' expect(subject.type).to eq :belongs_to expect(subject.klass).to eq MongoBlog expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to eq :mongo_blog_id expect(subject.foreign_key_nullable?).to be_truthy expect(subject.foreign_type).to be_nil expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to eq :mongo_blog_id expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end it 'distinguishes foreign_key column' do expect(@post.properties.detect { |f| f.name == :mongo_blog_id }.type).to eq(:bson_object_id) expect(@blog.properties.detect { |f| f.name == :mongo_blog_id }.type).to eq(:string) end end describe 'has_many association' do subject { @blog.associations.detect { |a| a.name == :mongo_posts } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo posts' expect(subject.type).to eq :has_many expect(subject.klass).to eq MongoPost expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to eq :mongo_blog_id expect(subject.foreign_key_nullable?).to be_truthy expect(subject.foreign_type).to be_nil expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to eq :mongo_post_ids expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end end describe 'has_and_belongs_to_many association' do subject { @post.associations.detect { |a| a.name == :mongo_categories } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo categories' expect(subject.type).to eq :has_and_belongs_to_many expect(subject.klass).to eq MongoCategory expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to eq :mongo_category_ids expect(subject.foreign_key_nullable?).to be_truthy expect(subject.foreign_type).to be_nil expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to eq :mongo_category_ids expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end end describe 'polymorphic belongs_to association' do before { allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[MongoBlog MongoPost MongoCategory MongoUser MongoProfile MongoComment]) } subject { @comment.associations.detect { |a| a.name == :commentable } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Commentable' expect(subject.type).to eq :belongs_to expect(subject.klass).to eq [MongoBlog, MongoPost] expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to eq :commentable_id expect(subject.foreign_key_nullable?).to be_truthy expect(subject.foreign_type).to eq :commentable_type expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to eq :commentable_id expect(subject.as).to be_nil expect(subject.polymorphic?).to be_truthy expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end describe 'on a subclass' do before do class MongoReview < MongoComment; end allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[MongoBlog MongoPost MongoCategory MongoUser MongoProfile MongoComment MongoReview]) end subject { RailsAdmin::AbstractModel.new(MongoReview).associations.detect { |a| a.name == :commentable } } it 'returns correct target klasses' do expect(subject.klass).to eq [MongoBlog, MongoPost] end end end describe 'polymorphic inverse has_many association' do before { allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[MongoBlog MongoPost MongoCategory MongoUser MongoProfile MongoComment]) } subject { @blog.associations.detect { |a| a.name == :mongo_comments } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo comments' expect(subject.type).to eq :has_many expect(subject.klass).to eq MongoComment expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to eq :commentable_id expect(subject.foreign_key_nullable?).to be_truthy expect(subject.foreign_type).to be_nil expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to eq :mongo_comment_ids expect(subject.as).to eq :commentable expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end it 'looks up correct inverse model' do expect(@category.associations.detect { |a| a.name == :librarian }.klass).to eq [MongoUser] expect(@blog.associations.detect { |a| a.name == :librarian }.klass).to eq [MongoProfile] end end describe 'embeds_one association' do subject { @post.associations.detect { |a| a.name == :mongo_note } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo note' expect(subject.type).to eq :has_one expect(subject.klass).to eq MongoNote expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to be_nil expect(subject.foreign_key_nullable?).to be_falsey expect(subject.foreign_type).to be_nil expect(subject.foreign_inverse_of).to be_nil expect(subject.key_accessor).to be_nil expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to eq(allow_destroy: false, update_only: false) end end describe 'embeds_many association' do subject { @user.associations.detect { |a| a.name == :mongo_notes } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Mongo notes' expect(subject.type).to eq :has_many expect(subject.klass).to eq MongoNote expect(subject.primary_key).to eq :_id expect(subject.foreign_key).to be_nil expect(subject.foreign_key_nullable?).to be_falsey expect(subject.foreign_type).to be_nil expect(subject.key_accessor).to be_nil expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to eq(allow_destroy: false, update_only: false) end it 'raises error when embeds_* is used without accepts_nested_attributes_for' do class MongoEmbedsOne include Mongoid::Document embeds_one :mongo_embedded end class MongoEmbedsMany include Mongoid::Document embeds_many :mongo_embeddeds end class MongoEmbedded include Mongoid::Document embedded_in :mongo_embeds_one embedded_in :mongo_embeds_many end class MongoRecursivelyEmbedsOne include Mongoid::Document recursively_embeds_one end class MongoRecursivelyEmbedsMany include Mongoid::Document recursively_embeds_many end expect { RailsAdmin::AbstractModel.new(MongoEmbedsOne).associations.first.nested_options }.to raise_error(RuntimeError, "Embedded association without accepts_nested_attributes_for can't be handled by RailsAdmin,\nbecause embedded model doesn't have top-level access.\nPlease add `accepts_nested_attributes_for :mongo_embedded' line to `MongoEmbedsOne' model.\n") expect { RailsAdmin::AbstractModel.new(MongoEmbedsMany).associations.first.nested_options }.to raise_error(RuntimeError, "Embedded association without accepts_nested_attributes_for can't be handled by RailsAdmin,\nbecause embedded model doesn't have top-level access.\nPlease add `accepts_nested_attributes_for :mongo_embeddeds' line to `MongoEmbedsMany' model.\n") expect { RailsAdmin::AbstractModel.new(MongoRecursivelyEmbedsOne).associations.first.nested_options }.not_to raise_error expect { RailsAdmin::AbstractModel.new(MongoRecursivelyEmbedsMany).associations.first.nested_options }.not_to raise_error end it 'works with inherited embeds_many model' do class MongoEmbedsParent include Mongoid::Document embeds_many :mongo_embeddeds accepts_nested_attributes_for :mongo_embeddeds end class MongoEmbedded include Mongoid::Document embedded_in :mongo_embeds_many end class MongoEmbedsChild < MongoEmbedsParent; end expect { RailsAdmin::AbstractModel.new(MongoEmbedsChild).associations }.not_to raise_error end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/mongoid/property_spec.rb
spec/rails_admin/adapters/mongoid/property_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::Adapters::Mongoid::Property', mongoid: true do subject { RailsAdmin::AbstractModel.new(FieldTest).properties.detect { |p| p.name == field } } describe '_id field' do let(:field) { :_id } it 'has correct values' do expect(subject.pretty_name).to eq ' id' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_truthy expect(subject.type).to eq :bson_object_id expect(subject.length).to be_nil end end describe 'array field' do let(:field) { :array_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Array field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :serialized expect(subject.length).to be_nil end end describe 'big decimal field' do let(:field) { :big_decimal_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Big decimal field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :decimal expect(subject.length).to be_nil end end describe 'boolean field' do let(:field) { :boolean_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Boolean field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :boolean expect(subject.length).to be_nil end end describe 'bson object id field' do let(:field) { :bson_object_id_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Bson object id field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :bson_object_id expect(subject.length).to be_nil end end describe 'date field' do let(:field) { :date_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Date field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :date expect(subject.length).to be_nil end end describe 'datetime field' do let(:field) { :datetime_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Datetime field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :datetime expect(subject.length).to be_nil end end describe 'time with zone field' do let(:field) { :time_with_zone_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Time with zone field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :datetime expect(subject.length).to be_nil end end describe 'default field' do let(:field) { :default_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Default field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :string expect(subject.length).to eq 255 end end describe 'float field' do let(:field) { :float_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Float field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :float expect(subject.length).to be_nil end end describe 'hash field' do let(:field) { :hash_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Hash field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :serialized expect(subject.length).to be_nil end end describe 'integer field' do let(:field) { :integer_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Integer field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :integer expect(subject.length).to be_nil end end describe 'object field' do let(:field) { :object_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Object field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :string expect(subject.length).to eq 255 end end describe 'string field' do let(:field) { :string_field } it 'has correct values' do expect(subject.pretty_name).to eq 'String field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :text expect(subject.length).to be_nil end end describe 'symbol field' do let(:field) { :symbol_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Symbol field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :string expect(subject.length).to eq 255 end end describe 'time field' do let(:field) { :time_field } it 'has correct values' do expect(subject.pretty_name).to eq 'Time field' expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey expect(subject.type).to eq :datetime expect(subject.length).to be_nil end end describe 'aliased field' do let(:field) { :aliased_field } it 'has correct values' do expect(subject.name).to eq :aliased_field expect(subject.pretty_name).to eq 'Aliased field' end end describe '#length_validation_lookup' do it 'detects validation length properly' do class LengthValiated include Mongoid::Document field :text, type: String validates :text, length: {maximum: 50} end expect(RailsAdmin::AbstractModel.new('LengthValiated').properties.last.send(:length_validation_lookup)).to eq(50) end it 'does not cause problem with custom validators' do class MyCustomValidator < ActiveModel::Validator def validate(_r); end end class CustomValiated include Mongoid::Document field :text, type: String validates_with MyCustomValidator end expect { RailsAdmin::AbstractModel.new('CustomValiated').properties.last.send(:length_validation_lookup) }.not_to raise_error end end describe '#read_only?' do before do class HasReadOnlyColumn include Mongoid::Document field :name, type: String attr_readonly :name end end it 'returns correct values' do expect(RailsAdmin::AbstractModel.new('Player').properties.detect { |f| f.name == :name }).not_to be_read_only expect(RailsAdmin::AbstractModel.new('HasReadOnlyColumn').properties.detect { |f| f.name == :name }).to be_read_only end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/active_record/object_extension_spec.rb
spec/rails_admin/adapters/active_record/object_extension_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'RailsAdmin::Adapters::ActiveRecord::ObjectExtension', active_record: true do describe '#assign_attributes' do let(:player) { Player.new } let(:object) { player.extend RailsAdmin::Adapters::ActiveRecord::ObjectExtension } it 'does not cause error with nil' do expect(object.assign_attributes(nil)).to be nil end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/active_record/association_spec.rb
spec/rails_admin/adapters/active_record/association_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'timecop' RSpec.describe 'RailsAdmin::Adapters::ActiveRecord::Association', active_record: true do before :all do RailsAdmin::AbstractModel.reset_polymorphic_parents class ARBlog < Tableless has_many :a_r_posts has_many :a_r_comments, as: :commentable belongs_to :librarian, polymorphic: true end class ARPost < Tableless belongs_to :a_r_blog has_and_belongs_to_many :a_r_categories has_many :a_r_comments, as: :commentable end class ARCategory < Tableless has_and_belongs_to_many :a_r_posts, -> { readonly } has_and_belongs_to_many :scoped_posts, ->(category) { where(id: category.id) }, class_name: 'ARPost' belongs_to :librarian, polymorphic: true end class ARUser < Tableless has_one :a_r_profile has_many :a_r_categories, as: :librarian end class ARProfile < Tableless belongs_to :a_r_user has_many :a_r_blogs, as: :librarian end class ARComment < Tableless belongs_to :commentable, polymorphic: true end @blog = RailsAdmin::AbstractModel.new(ARBlog) @post = RailsAdmin::AbstractModel.new(ARPost) @category = RailsAdmin::AbstractModel.new(ARCategory) @user = RailsAdmin::AbstractModel.new(ARUser) @profile = RailsAdmin::AbstractModel.new(ARProfile) @comment = RailsAdmin::AbstractModel.new(ARComment) end after :all do RailsAdmin::AbstractModel.reset_polymorphic_parents end it 'lists associations' do expect(@post.associations.collect { |a| a.name.to_s }).to include(*%w[a_r_blog a_r_categories a_r_comments]) end it 'list associations types in supported [:belongs_to, :has_and_belongs_to_many, :has_many, :has_one]' do # ActiveRecord 4.1 converts has_and_belongs_to_many association to has_many expect((@post.associations + @blog.associations + @user.associations).collect(&:type).uniq.collect(&:to_s)).to include(*%w[belongs_to has_many has_one]) end describe 'belongs_to association' do subject { @post.associations.detect { |a| a.name == :a_r_blog } } it 'returns correct values' do expect(subject.pretty_name).to eq 'A r blog' expect(subject.type).to eq :belongs_to expect(subject.klass).to eq ARBlog expect(subject.primary_key).to eq :id expect(subject.foreign_key).to eq :a_r_blog_id expect(subject.foreign_type).to be_nil expect(subject.key_accessor).to eq :a_r_blog_id expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end end describe 'has_many association' do subject { @blog.associations.detect { |a| a.name == :a_r_posts } } it 'returns correct values' do expect(subject.pretty_name).to eq 'A r posts' expect(subject.type).to eq :has_many expect(subject.klass).to eq ARPost expect(subject.primary_key).to eq :id expect(subject.foreign_key).to eq :ar_blog_id expect(subject.foreign_type).to be_nil expect(subject.key_accessor).to eq :a_r_post_ids expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end end describe 'has_many association' do let(:league) { RailsAdmin::AbstractModel.new(League) } context 'for direct has many' do let(:association) { league.associations.detect { |a| a.name == :divisions } } it 'returns correct values' do expect(association.type).to eq :has_many expect(association.klass).to eq Division expect(association.read_only?).to be_falsey expect(association.foreign_key_nullable?).to be_truthy end end context 'for has many through marked as readonly' do let(:association) { league.associations.detect { |a| a.name == :teams } } it 'returns correct values' do expect(association.type).to eq :has_many expect(association.klass).to eq Team expect(association.read_only?).to be_truthy expect(association.foreign_key_nullable?).to be_truthy end end context 'for has many through multiple associations' do let(:association) { league.associations.detect { |a| a.name == :players } } it 'returns correct values' do expect(association.type).to eq :has_many expect(association.klass).to eq Player expect(association.read_only?).to be_truthy end end end describe 'has_many association with not nullable foreign key' do let(:field_test) { RailsAdmin::AbstractModel.new(FieldTest) } let(:association) { field_test.associations.detect { |a| a.name == :nested_field_tests } } context 'for direct has many' do it 'returns correct values' do expect(association.foreign_key_nullable?).to be_falsey end end context 'when foreign_key is passed as Symbol' do before do class FieldTestWithSymbolForeignKey < FieldTest has_many :nested_field_tests, dependent: :destroy, inverse_of: :field_test, foreign_key: :field_test_id end end let(:field_test) { RailsAdmin::AbstractModel.new(FieldTestWithSymbolForeignKey) } it 'does not break' do expect(association.foreign_key_nullable?).to be_falsey end end end describe 'has_and_belongs_to_many association' do subject { @post.associations.detect { |a| a.name == :a_r_categories } } it 'returns correct values' do expect(subject.pretty_name).to eq 'A r categories' expect(subject.klass).to eq ARCategory expect(subject.primary_key).to eq :id expect(subject.foreign_type).to be_nil expect(subject.foreign_key_nullable?).to be_truthy expect(subject.key_accessor).to eq :a_r_category_ids expect(subject.as).to be_nil expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end context 'with a scope given' do subject { @category.associations.detect { |a| a.name == :a_r_posts } } it 'does not break' do expect(subject.read_only?).to be_truthy end end context 'with a scope that receives an argument given' do subject { @category.associations.detect { |a| a.name == :scoped_posts } } it 'ignores the scope' do expect(subject.read_only?).to be_falsey end end end describe 'polymorphic belongs_to association' do before { allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[ARBlog ARPost ARCategory ARUser ARProfile ARComment]) } subject { @comment.associations.detect { |a| a.name == :commentable } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Commentable' expect(subject.type).to eq :belongs_to expect(subject.klass).to eq [ARBlog, ARPost] expect(subject.primary_key).to be_nil expect(subject.foreign_key).to eq :commentable_id expect(subject.foreign_type).to eq :commentable_type expect(subject.key_accessor).to eq :commentable_id expect(subject.as).to be_nil expect(subject.polymorphic?).to be_truthy expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end it 'looks up correct inverse model' do expect(@category.associations.detect { |a| a.name == :librarian }.klass).to eq [ARUser] expect(@blog.associations.detect { |a| a.name == :librarian }.klass).to eq [ARProfile] end describe 'on a subclass' do before do class ARReview < ARComment; end allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[ARBlog ARPost ARCategory ARUser ARProfile ARComment ARReview]) end subject { RailsAdmin::AbstractModel.new(ARReview).associations.detect { |a| a.name == :commentable } } it 'returns correct target klasses' do expect(subject.klass).to eq [ARBlog, ARPost] end end end describe 'polymorphic inverse has_many association' do subject { @blog.associations.detect { |a| a.name == :a_r_comments } } it 'returns correct values' do expect(subject.pretty_name).to eq 'A r comments' expect(subject.type).to eq :has_many expect(subject.klass).to eq ARComment expect(subject.primary_key).to eq :id expect(subject.foreign_key).to eq :commentable_id expect(subject.foreign_type).to be_nil expect(subject.key_accessor).to eq :a_r_comment_ids expect(subject.as).to eq :commentable expect(subject.polymorphic?).to be_falsey expect(subject.inverse_of).to be_nil expect(subject.read_only?).to be_falsey expect(subject.nested_options).to be_nil end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false
railsadminteam/rails_admin
https://github.com/railsadminteam/rails_admin/blob/d8e0809ea4b38415ace5b0d038fca317d805a3c1/spec/rails_admin/adapters/active_record/property_spec.rb
spec/rails_admin/adapters/active_record/property_spec.rb
# frozen_string_literal: true require 'spec_helper' require 'timecop' RSpec.describe 'RailsAdmin::Adapters::ActiveRecord::Property', active_record: true do describe 'string field' do subject { RailsAdmin::AbstractModel.new('Player').properties.detect { |f| f.name == :name } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Name' expect(subject.type).to eq :string expect(subject.length).to eq 100 expect(subject.nullable?).to be_falsey expect(subject.serial?).to be_falsey end end describe 'serialized field' do subject { RailsAdmin::AbstractModel.new('User').properties.detect { |f| f.name == :roles } } it 'returns correct values' do expect(subject.pretty_name).to eq 'Roles' expect(subject.type).to eq :serialized expect(subject.nullable?).to be_truthy expect(subject.serial?).to be_falsey end end describe '#read_only?' do before do class HasReadOnlyColumn < Tableless column :name, :varchar attr_readonly :name end end it 'returns correct values' do expect(RailsAdmin::AbstractModel.new('Player').properties.detect { |f| f.name == :name }).not_to be_read_only expect(RailsAdmin::AbstractModel.new('HasReadOnlyColumn').properties.detect { |f| f.name == :name }).to be_read_only end end end
ruby
MIT
d8e0809ea4b38415ace5b0d038fca317d805a3c1
2026-01-04T15:39:16.877032Z
false