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 |
|---|---|---|---|---|---|---|---|---|
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/request/templates/request_spec.rb | lib/generators/rspec/request/templates/request_spec.rb | require 'rails_helper'
RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do
describe "GET /<%= name.underscore.pluralize %>" do
it "works! (now write some real specs)" do
get <%= index_helper %>_path
expect(response).to have_http_status(200)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/job/job_generator.rb | lib/generators/rspec/job/job_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class JobGenerator < Base
def create_job_spec
file_suffix = file_name.end_with?('job') ? 'spec.rb' : 'job_spec.rb'
template 'job_spec.rb.erb', target_path('jobs', class_path, [file_name, file_suffix].join('_'))
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/install/install_generator.rb | lib/generators/rspec/install/install_generator.rb | require "rspec/support"
require "rspec/core"
RSpec::Support.require_rspec_core "project_initializer"
require "rspec/rails/feature_check"
module Rspec
module Generators
# @private
class InstallGenerator < ::Rails::Generators::Base
desc <<DESC
Description:
Copy rspec files to your application.
DESC
class_option :default_path, type: :string, default: 'spec'
def self.source_root
@source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
end
def copy_spec_files
Dir.mktmpdir do |dir|
generate_rspec_init dir
template File.join(dir, '.rspec'), '.rspec'
directory File.join(dir, 'spec'), default_path
end
end
def copy_rails_files
template 'spec/rails_helper.rb', "#{default_path}/rails_helper.rb"
end
private
def generate_rspec_init(tmpdir)
initializer = ::RSpec::Core::ProjectInitializer.new(
destination: tmpdir,
report_stream: StringIO.new
)
initializer.run
spec_helper_path = File.join(tmpdir, 'spec', 'spec_helper.rb')
replace_generator_command(spec_helper_path)
remove_warnings_configuration(spec_helper_path)
unless default_path == "spec"
dot_rspec_path = File.join(tmpdir, '.rspec')
append_default_path(dot_rspec_path)
end
end
def replace_generator_command(spec_helper_path)
gsub_file spec_helper_path,
'rspec --init',
'rails generate rspec:install',
verbose: false
end
def remove_warnings_configuration(spec_helper_path)
empty_line = '^\n'
comment_line = '^\s*#.+\n'
gsub_file spec_helper_path,
/#{empty_line}(#{comment_line})+\s+config\.warnings = true\n/,
'',
verbose: false
end
def append_default_path(dot_rspec_path)
append_to_file dot_rspec_path,
"--default-path #{default_path}"
end
def default_path
options[:default_path]
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/install/templates/spec/rails_helper.rb | lib/generators/rspec/install/templates/spec/rails_helper.rb | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
<% if RSpec::Rails::FeatureCheck.has_active_record_migration? -%>
# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file
# that will avoid rails generators crashing because migrations haven't been run yet
# return unless Rails.env.test?
<% end -%>
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }
<% if RSpec::Rails::FeatureCheck.has_active_record_migration? -%>
# Ensures that the test database schema matches the current schema file.
# If there are pending migrations it will invoke `db:test:prepare` to
# recreate the test database by loading the schema.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
abort e.to_s.strip
end
<% end -%>
RSpec.configure do |config|
<% if RSpec::Rails::FeatureCheck.has_active_record? -%>
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_paths = [
Rails.root.join('spec/fixtures')
]
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
<% else -%>
# Remove this line to enable support for ActiveRecord
config.use_active_record = false
# If you enable ActiveRecord support you should uncomment these lines,
# note if you'd prefer not to run each example within a transaction, you
# should set use_transactional_fixtures to false.
#
# config.fixture_paths = [
# Rails.root.join('spec/fixtures')
# ]
# config.use_transactional_fixtures = true
<% end -%>
# RSpec Rails uses metadata to mix in different behaviours to your tests,
# for example enabling you to call `get` and `post` in request specs. e.g.:
#
# RSpec.describe UsersController, type: :request do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://rspec.info/features/8-0/rspec-rails
#
# You can also infer these behaviours automatically by location, e.g.
# /spec/models would pull in the same behaviour as `type: :model` but this
# behaviour is considered legacy and will be removed in a future version.
#
# To enable this behaviour uncomment the line below.
# config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/test_helper.rb | test/test_helper.rb | # Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require 'bundler/setup'
require 'rails'
require 'rails/test_help'
require 'rails-api'
def rails3?
Rails::API.rails3?
end
class ActiveSupport::TestCase
def self.app
@@app ||= Class.new(Rails::Application) do
def self.name
'TestApp'
end
end.tap do |app|
config = app.config
config.active_support.deprecation = :stderr
config.active_support.test_order = :random
config.generators do |c|
c.orm :active_record, :migration => true,
:timestamps => true
c.test_framework :test_unit, :fixture => true,
:fixture_replacement => nil
c.integration_tool :test_unit
c.performance_tool :test_unit
end
unless rails3?
config.eager_load = false
config.secret_key_base = 'abc123'
end
end
end
def app
self.class.app
end
app.routes.append do
get ':controller(/:action)'
end
app.routes.finalize!
app.load_generators
end
module ActionController
class API
include ActiveSupport::TestCase.app.routes.url_helpers
end
end
Rails.logger = Logger.new("/dev/null")
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_application/api_application_test.rb | test/api_application/api_application_test.rb | require 'test_helper'
require 'action_controller/railtie'
require 'rack/test'
class OmgController < ActionController::API
def index
render :text => "OMG"
end
def unauthorized
render :text => "get out", :status => :unauthorized
end
end
class ApiApplicationTest < ActiveSupport::TestCase
include ::Rack::Test::Methods
app.initialize!
def test_boot_api_app
get "/omg"
assert_equal "OMG", last_response.body
end
def test_proper_status_set
get "/omg/unauthorized"
assert_equal 401, last_response.status
end
def test_api_middleware_stack
expected_middleware_stack =
rails3? ? expected_middleware_stack_rails3 : expected_middleware_stack_rails
assert_equal expected_middleware_stack, app.middleware.map(&:klass).map(&:name)
end
private
def expected_middleware_stack_rails3
[
"ActionDispatch::Static",
"Rack::Lock",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"ActionDispatch::RequestId",
"Rails::Rack::Logger",
"ActionDispatch::ShowExceptions",
"ActionDispatch::DebugExceptions",
"ActionDispatch::RemoteIp",
"ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
"ActionDispatch::ParamsParser",
"ActionDispatch::Head",
"Rack::ConditionalGet",
"Rack::ETag"
]
end
def expected_middleware_stack_rails
[
"ActionDispatch::Static",
"Rack::Lock",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"ActionDispatch::RequestId",
"Rails::Rack::Logger",
"ActionDispatch::ShowExceptions",
"ActionDispatch::DebugExceptions",
"ActionDispatch::RemoteIp",
"ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
"ActionDispatch::ParamsParser",
"Rack::Head",
"Rack::ConditionalGet",
"Rack::ETag",
]
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/generators/app_generator_test.rb | test/generators/app_generator_test.rb | require 'generators/generators_test_helper'
require 'rails-api/generators/rails/app/app_generator'
class AppGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments [destination_root]
def test_skeleton_is_created
run_generator
default_files.each { |path| assert_file path }
skipped_files.each { |path| assert_no_file path }
end
def test_api_modified_files
run_generator
assert_file "Gemfile" do |content|
assert_match(/gem 'rails-api'/, content)
assert_no_match(/gem 'coffee-rails'/, content)
assert_no_match(/gem 'jquery-rails'/, content)
assert_no_match(/gem 'sass-rails'/, content)
end
assert_file "app/controllers/application_controller.rb", /ActionController::API/
end
private
def default_files
files = %W(
.gitignore
Gemfile
Rakefile
config.ru
app/controllers
app/mailers
app/models
config/environments
config/initializers
config/locales
db
lib
lib/tasks
lib/assets
log
test/fixtures
test/#{generated_test_functional_dir}
test/integration
test/#{generated_test_unit_dir}
)
files.concat rails3? ? default_files_rails3 : default_files_rails
files
end
def default_files_rails3
%w(script/rails)
end
def default_files_rails
%w(bin/bundle bin/rails bin/rake)
end
def skipped_files
%w(vendor/assets
tmp/cache/assets)
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/generators/generators_test_helper.rb | test/generators/generators_test_helper.rb | require 'test_helper'
require 'rails/generators'
module GeneratorsTestHelper
def self.included(base)
base.class_eval do
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
teardown :remove_destination
begin
base.tests Rails::Generators.const_get(base.name.sub(/Test$/, ''))
rescue
end
end
end
private
def copy_routes
routes = File.expand_path("../fixtures/routes.rb", __FILE__)
destination = File.join(destination_root, "config")
FileUtils.mkdir_p(destination)
FileUtils.cp routes, destination
end
def generated_test_unit_dir
rails3? ? 'unit' : 'models'
end
def generated_test_functional_dir
rails3? ? 'functional' : 'controllers'
end
def remove_destination
rm_rf destination_root
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/generators/resource_generator_test.rb | test/generators/resource_generator_test.rb | require 'generators/generators_test_helper'
require 'rails/generators/rails/resource/resource_generator'
class ResourceGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments %w(account)
setup :copy_routes
def test_resource_routes_are_added
run_generator
assert_file "config/routes.rb" do |route|
assert_match(/resources :accounts, except: \[:new, :edit\]$/, route)
assert_no_match(/resources :accounts$/, route)
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/generators/scaffold_generator_test.rb | test/generators/scaffold_generator_test.rb | require 'generators/generators_test_helper'
require 'rails/generators/rails/scaffold/scaffold_generator'
class ScaffoldGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments %w(product_line title:string product:belongs_to user:references)
setup :copy_routes
def test_scaffold_on_invoke
run_generator
# Model
assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
assert_file "test/#{generated_test_unit_dir}/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
if rails3?
assert_migration "db/migrate/create_product_lines.rb",
/belongs_to :product/,
/add_index :product_lines, :product_id/,
/references :user/,
/add_index :product_lines, :user_id/
else
assert_migration "db/migrate/create_product_lines.rb",
/belongs_to :product, index: true/,
/references :user, index: true/
end
# Route
assert_file "config/routes.rb" do |content|
assert_match(/resources :product_lines, except: \[:new, :edit\]$/, content)
assert_no_match(/resource :product_lines$/, content)
end
# Controller
assert_file "app/controllers/product_lines_controller.rb" do |content|
assert_match(/class ProductLinesController < ApplicationController/, content)
assert_no_match(/respond_to/, content)
assert_match(/before_action :set_product_line, only: \[:show, :update, :destroy\]/, content)
assert_instance_method :index, content do |m|
assert_match(/@product_lines = ProductLine\.all/, m)
assert_match(/render json: @product_lines/, m)
end
assert_instance_method :show, content do |m|
assert_match(/render json: @product_line/, m)
end
assert_instance_method :create, content do |m|
assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m)
assert_match(/@product_line\.save/, m)
assert_match(/@product_line\.errors/, m)
end
assert_instance_method :update, content do |m|
if rails3?
assert_match(/@product_line\.update_attributes\(params\[:product_line\]\)/, m)
else
assert_match(/@product_line\.update\(product_line_params\)/, m)
end
assert_match(/@product_line\.errors/, m)
end
assert_instance_method :destroy, content do |m|
assert_match(/@product_line\.destroy/, m)
end
unless rails3?
assert_instance_method :set_product_line, content do |m|
assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
end
assert_instance_method :product_line_params, content do |m|
assert_match(/params\.require\(:product_line\)\.permit\(:title, :product_id, :user_id\)/, m)
end
end
end
assert_file "test/#{generated_test_functional_dir}/product_lines_controller_test.rb" do |test|
assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
if rails3?
if RUBY_VERSION < "1.9"
assert_match(/post :create, product_line: \{ :title => @product_line.title \}/, test)
assert_match(/put :update, id: @product_line, product_line: \{ :title => @product_line.title \}/, test)
else
assert_match(/post :create, product_line: \{ title: @product_line.title \}/, test)
assert_match(/put :update, id: @product_line, product_line: \{ title: @product_line.title \}/, test)
end
else
assert_match(/post :create, product_line: \{ product_id: @product_line.product_id, title: @product_line.title, user_id: @product_line.user_id \}/, test)
assert_match(/put :update, id: @product_line, product_line: \{ product_id: @product_line.product_id, title: @product_line.title, user_id: @product_line.user_id \}/, test)
end
assert_no_match(/assert_redirected_to/, test)
end
# Views
%w(index edit new show _form).each do |view|
assert_no_file "app/views/product_lines/#{view}.html.erb"
end
assert_no_file "app/views/layouts/product_lines.html.erb"
# Helpers
assert_no_file "app/helpers/product_lines_helper.rb"
assert_no_file "test/#{generated_test_unit_dir}/helpers/product_lines_helper_test.rb"
# Assets
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/product_lines.css"
assert_no_file "app/assets/javascripts/product_lines.js"
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/generators/fixtures/routes.rb | test/generators/fixtures/routes.rb | Rails.application.routes.draw do
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/url_for_test.rb | test/api_controller/url_for_test.rb | require 'test_helper'
class UrlForApiController < ActionController::API
def one; end
def two; end
end
class UrlForApiTest < ActionController::TestCase
tests UrlForApiController
def setup
super
@request.host = 'www.example.com'
end
def test_url_for
get :one
assert_equal "http://www.example.com/url_for_api/one", @controller.url_for
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/renderers_test.rb | test/api_controller/renderers_test.rb | require 'test_helper'
require 'active_support/core_ext/hash/conversions'
class Model
def to_json(options = {})
{ :a => 'b' }.to_json(options)
end
def to_xml(options = {})
{ :a => 'b' }.to_xml(options)
end
end
class RenderersApiController < ActionController::API
use ActionDispatch::ShowExceptions, Rails::API::PublicExceptions.new(Rails.public_path)
def one
render :json => Model.new
end
def two
render :xml => Model.new
end
def boom
raise "boom"
end
end
class RenderersApiTest < ActionController::TestCase
tests RenderersApiController
def test_render_json
get :one
assert_response :success
assert_equal({ :a => 'b' }.to_json, @response.body)
end
def test_render_xml
get :two
assert_response :success
assert_equal({ :a => 'b' }.to_xml, @response.body)
end
end
class RenderExceptionsTest < ActionDispatch::IntegrationTest
def setup
@app = RenderersApiController.action(:boom)
end
def test_render_json_exception
get "/fake", {}, 'HTTP_ACCEPT' => 'application/json'
assert_response :internal_server_error
assert_equal 'application/json', response.content_type.to_s
assert_equal({ :status => '500', :error => 'boom' }.to_json, response.body)
end
def test_render_xml_exception
get "/fake", {}, 'HTTP_ACCEPT' => 'application/xml'
assert_response :internal_server_error
assert_equal 'application/xml', response.content_type.to_s
assert_equal({ :status => '500', :error => 'boom' }.to_xml, response.body)
end
def test_render_fallback_exception
get "/fake", {}, 'HTTP_ACCEPT' => 'text/csv'
assert_response :internal_server_error
assert_equal 'text/html', response.content_type.to_s
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/force_ssl_test.rb | test/api_controller/force_ssl_test.rb | require 'test_helper'
class ForceSSLApiController < ActionController::API
force_ssl
def one; end
def two
head :ok
end
end
class ForceSSLApiTest < ActionController::TestCase
tests ForceSSLApiController
def test_redirects_to_https
get :two
assert_response 301
assert_equal "https://test.host/force_ssl_api/two", redirect_to_url
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/redirect_to_test.rb | test/api_controller/redirect_to_test.rb | require 'test_helper'
class RedirectToApiController < ActionController::API
def one
redirect_to :action => "two"
end
def two; end
end
class RedirectToApiTest < ActionController::TestCase
tests RedirectToApiController
def test_redirect_to
get :one
assert_response :redirect
assert_equal "http://test.host/redirect_to_api/two", redirect_to_url
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/data_streaming_test.rb | test/api_controller/data_streaming_test.rb | require 'test_helper'
module TestApiFileUtils
def file_name() File.basename(__FILE__) end
def file_path() File.expand_path(__FILE__) end
def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
end
class DataStreamingApiController < ActionController::API
include TestApiFileUtils
def one; end
def two
send_data(file_data, {})
end
end
class DataStreamingApiTest < ActionController::TestCase
include TestApiFileUtils
tests DataStreamingApiController
def test_data
response = process('two')
assert_kind_of String, response.body
assert_equal file_data, response.body
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/action_methods_test.rb | test/api_controller/action_methods_test.rb | require 'test_helper'
class ActionMethodsApiController < ActionController::API
def one; end
def two; end
# Rails 5 does not have method hide_action
if Rails::VERSION::MAJOR < 5
hide_action :two
end
end
class ActionMethodsApiTest < ActionController::TestCase
tests ActionMethodsApiController
def test_action_methods
if Rails::VERSION::MAJOR < 5
assert_equal Set.new(%w(one)),
@controller.class.action_methods,
"#{@controller.controller_path} should not be empty!"
else
assert_equal Set.new(%w(one two)),
@controller.class.action_methods,
"#{@controller.controller_path} should not be empty!"
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/test/api_controller/conditional_get_test.rb | test/api_controller/conditional_get_test.rb | require 'test_helper'
require 'active_support/core_ext/integer/time'
require 'active_support/core_ext/numeric/time'
class ConditionalGetApiController < ActionController::API
before_filter :handle_last_modified_and_etags, :only => :two
def one
if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123])
render :text => "Hi!"
end
end
def two
render :text => "Hi!"
end
private
def handle_last_modified_and_etags
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
end
class ConditionalGetApiTest < ActionController::TestCase
tests ConditionalGetApiController
def setup
@last_modified = Time.now.utc.beginning_of_day.httpdate
end
def test_request_with_bang_gets_last_modified
get :two
assert_equal @last_modified, @response.headers['Last-Modified']
assert_response :success
end
def test_request_with_bang_obeys_last_modified
@request.if_modified_since = @last_modified
get :two
assert_response :not_modified
end
def test_last_modified_works_with_less_than_too
@request.if_modified_since = 5.years.ago.httpdate
get :two
assert_response :success
end
def test_request_not_modified
@request.if_modified_since = @last_modified
get :one
assert_equal 304, @response.status.to_i
assert @response.body.blank?
assert_equal @last_modified, @response.headers['Last-Modified']
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api.rb | lib/rails-api.rb | require 'rails/version'
require 'rails-api/version'
require 'rails-api/action_controller/api'
require 'rails-api/application'
module Rails
module API
def self.rails3?
Rails::VERSION::MAJOR == 3
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/public_exceptions.rb | lib/rails-api/public_exceptions.rb | module Rails
module API
class PublicExceptions
attr_accessor :public_path
def initialize(public_path)
@public_path = public_path
end
def call(env)
exception = env["action_dispatch.exception"]
status = env["PATH_INFO"][1..-1]
request = ActionDispatch::Request.new(env)
content_type = request.formats.first
body = { :status => status, :error => exception.message }
render(status, content_type, body)
end
private
def render(status, content_type, body)
format = content_type && "to_#{content_type.to_sym}"
if format && body.respond_to?(format)
render_format(status, content_type, body.send(format))
else
render_html(status)
end
end
def render_format(status, content_type, body)
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
'Content-Length' => body.bytesize.to_s}, [body]]
end
def render_html(status)
found = false
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
if found || File.exist?(path)
render_format(status, 'text/html', File.read(path))
else
[404, { "X-Cascade" => "pass" }, []]
end
end
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/version.rb | lib/rails-api/version.rb | module Rails
module API
VERSION = '0.4.1'
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/application.rb | lib/rails-api/application.rb | require 'rails/application'
require 'rails-api/public_exceptions'
require 'rails-api/application/default_rails_four_middleware_stack'
module Rails
class Application < Engine
alias_method :rails_default_middleware_stack, :default_middleware_stack
def default_middleware_stack
if Rails::API.rails3?
rails3_stack
else
DefaultRailsFourMiddlewareStack.new(self, config, paths).build_stack
end
end
def setup_generators!
generators = config.generators
generators.templates.unshift File::expand_path('../templates', __FILE__)
generators.resource_route = :api_resource_route
generators.hide_namespace "css"
generators.rails({
:helper => false,
:assets => false,
:stylesheets => false,
:stylesheet_engine => nil,
:template_engine => nil
})
end
ActiveSupport.on_load(:before_configuration) do
config.api_only = true
setup_generators!
end
private
def check_serve_static_files
if Rails::VERSION::MAJOR >= 5 || (Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR > 1)
config.serve_static_files
else
config.serve_static_assets
end
end
def rails3_stack
ActionDispatch::MiddlewareStack.new.tap do |middleware|
if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
require "action_dispatch/http/rack_cache"
middleware.use ::Rack::Cache, rack_cache
end
if config.force_ssl
require "rack/ssl"
middleware.use ::Rack::SSL, config.ssl_options
end
if config.action_dispatch.x_sendfile_header.present?
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
end
if check_serve_static_files
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
end
middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride unless config.api_only
middleware.use ::ActionDispatch::RequestId
middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || Rails::API::PublicExceptions.new(Rails.public_path)
middleware.use ::ActionDispatch::DebugExceptions
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
unless config.cache_classes
app = self
middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
end
middleware.use ::ActionDispatch::Callbacks
middleware.use ::ActionDispatch::Cookies unless config.api_only
if !config.api_only && config.session_store
if config.force_ssl && !config.session_options.key?(:secure)
config.session_options[:secure] = true
end
middleware.use config.session_store, config.session_options
middleware.use ::ActionDispatch::Flash
end
middleware.use ::ActionDispatch::ParamsParser
middleware.use ::ActionDispatch::Head
middleware.use ::Rack::ConditionalGet
middleware.use ::Rack::ETag, "no-cache"
if !config.api_only && config.action_dispatch.best_standards_support
middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support
end
end
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/application/default_rails_four_middleware_stack.rb | lib/rails-api/application/default_rails_four_middleware_stack.rb | module Rails
class Application
class DefaultRailsFourMiddlewareStack
attr_reader :config, :paths, :app
def initialize(app, config, paths)
@app = app
@config = config
@paths = paths
end
def build_stack
ActionDispatch::MiddlewareStack.new.tap do |middleware|
if rack_cache = load_rack_cache
require "action_dispatch/http/rack_cache"
middleware.use ::Rack::Cache, rack_cache
end
if config.force_ssl
middleware.use ::ActionDispatch::SSL, config.ssl_options
end
if config.action_dispatch.x_sendfile_header.present?
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
end
if serve_static_files?
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
end
middleware.use ::Rack::Lock unless allow_concurrency?
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride unless config.api_only
middleware.use ::ActionDispatch::RequestId
# Must come after Rack::MethodOverride to properly log overridden methods
middleware.use ::Rails::Rack::Logger, config.log_tags
middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
middleware.use ::ActionDispatch::DebugExceptions, app
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
unless config.cache_classes
middleware.use ::ActionDispatch::Reloader, lambda { reload_dependencies? }
end
middleware.use ::ActionDispatch::Callbacks
middleware.use ::ActionDispatch::Cookies unless config.api_only
if !config.api_only && config.session_store
if config.force_ssl && !config.session_options.key?(:secure)
config.session_options[:secure] = true
end
middleware.use config.session_store, config.session_options
middleware.use ::ActionDispatch::Flash
end
middleware.use ::ActionDispatch::ParamsParser
middleware.use ::Rack::Head
middleware.use ::Rack::ConditionalGet
middleware.use ::Rack::ETag, "no-cache"
end
end
private
# `config.serve_static_assets` will be removed in Rails 5.0, and throws
# a deprecation warning in Rails >= 4.2. The new option is
# `config.serve_static_files`.
def serve_static_files?
if config.respond_to?(:serve_static_files)
config.serve_static_files
else
config.serve_static_assets
end
end
def reload_dependencies?
config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
end
def allow_concurrency?
config.allow_concurrency.nil? ? config.cache_classes : config.allow_concurrency
end
def load_rack_cache
rack_cache = config.action_dispatch.rack_cache
return unless rack_cache
begin
require 'rack/cache'
rescue LoadError => error
error.message << ' Be sure to add rack-cache to your Gemfile'
raise
end
if rack_cache == true
{
:metastore => "rails:/",
:entitystore => "rails:/",
:verbose => false
}
else
rack_cache
end
end
def show_exceptions_app
config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
end
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/generators/rails/app/app_generator.rb | lib/rails-api/generators/rails/app/app_generator.rb | require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
Rails::Generators::AppGenerator.source_paths.unshift(
File.expand_path('../../../../templates/rails/app', __FILE__)
)
class Rails::AppBuilder
undef tmp
undef vendor
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/templates/rails/scaffold_controller/controller.rb | lib/rails-api/templates/rails/scaffold_controller/controller.rb | <% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
before_action <%= ":set_#{singular_table_name}" %>, only: [:show, :update, :destroy]
# GET <%= route_url %>
# GET <%= route_url %>.json
def index
@<%= plural_table_name %> = <%= orm_class.all(class_name) %>
render json: <%= "@#{plural_table_name}" %>
end
# GET <%= route_url %>/1
# GET <%= route_url %>/1.json
def show
render json: <%= "@#{singular_table_name}" %>
end
# POST <%= route_url %>
# POST <%= route_url %>.json
def create
@<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %>
if @<%= orm_instance.save %>
render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %>
else
render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
end
end
# PATCH/PUT <%= route_url %>/1
# PATCH/PUT <%= route_url %>/1.json
def update
if @<%= Rails::API.rails3? ? orm_instance.update_attributes("params[:#{singular_table_name}]") : orm_instance.update("#{singular_table_name}_params") %>
head :no_content
else
render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
end
end
# DELETE <%= route_url %>/1
# DELETE <%= route_url %>/1.json
def destroy
@<%= orm_instance.destroy %>
head :no_content
end
private
def <%= "set_#{singular_table_name}" %>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
end
def <%= "#{singular_table_name}_params" %>
<%- if defined?(attributes_names) -%>
params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
<%- else -%>
params[:<%= singular_table_name %>]
<%- end -%>
end
end
<% end -%>
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/templates/test_unit/scaffold/functional_test.rb | lib/rails-api/templates/test_unit/scaffold/functional_test.rb | require 'test_helper'
<% module_namespacing do -%>
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
setup do
@<%= singular_table_name %> = <%= table_name %>(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:<%= table_name %>)
end
test "should create <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count') do
post :create, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
end
assert_response 201
end
test "should show <%= singular_table_name %>" do
get :show, id: <%= "@#{singular_table_name}" %>
assert_response :success
end
test "should update <%= singular_table_name %>" do
put :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
assert_response 204
end
test "should destroy <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count', -1) do
delete :destroy, id: <%= "@#{singular_table_name}" %>
end
assert_response 204
end
end
<% end -%>
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/rails-api/action_controller/api.rb | lib/rails-api/action_controller/api.rb | require 'action_view'
require 'action_controller'
require 'action_controller/log_subscriber'
module ActionController
# API Controller is a lightweight version of <tt>ActionController::Base</tt>,
# created for applications that don't require all functionality that a complete
# \Rails controller provides, allowing you to create faster controllers for
# example for API only applications.
#
# An API Controller is different from a normal controller in the sense that
# by default it doesn't include a number of features that are usually required
# by browser access only: layouts and templates rendering, cookies, sessions,
# flash, assets, and so on. This makes the entire controller stack thinner and
# faster, suitable for API applications. It doesn't mean you won't have such
# features if you need them: they're all available for you to include in
# your application, they're just not part of the default API Controller stack.
#
# By default, only the ApplicationController in a \Rails application inherits
# from <tt>ActionController::API</tt>. All other controllers in turn inherit
# from ApplicationController.
#
# A sample controller could look like this:
#
# class PostsController < ApplicationController
# def index
# @posts = Post.all
# render json: @posts
# end
# end
#
# Request, response and parameters objects all work the exact same way as
# <tt>ActionController::Base</tt>.
#
# == Renders
#
# The default API Controller stack includes all renderers, which means you
# can use <tt>render :json</tt> and brothers freely in your controllers. Keep
# in mind that templates are not going to be rendered, so you need to ensure
# your controller is calling either <tt>render</tt> or <tt>redirect</tt> in
# all actions.
#
# def show
# @post = Post.find(params[:id])
# render json: @post
# end
#
# == Redirects
#
# Redirects are used to move from one action to another. You can use the
# <tt>redirect</tt> method in your controllers in the same way as
# <tt>ActionController::Base</tt>. For example:
#
# def create
# redirect_to root_url and return if not_authorized?
# # do stuff here
# end
#
# == Adding new behavior
#
# In some scenarios you may want to add back some functionality provided by
# <tt>ActionController::Base</tt> that is not present by default in
# <tt>ActionController::API</tt>, for instance <tt>MimeResponds</tt>. This
# module gives you the <tt>respond_to</tt> and <tt>respond_with</tt> methods.
# Adding it is quite simple, you just need to include the module in a specific
# controller or in <tt>ApplicationController</tt> in case you want it
# available to your entire app:
#
# class ApplicationController < ActionController::API
# include ActionController::MimeResponds
# end
#
# class PostsController < ApplicationController
# respond_to :json, :xml
#
# def index
# @posts = Post.all
# respond_with @posts
# end
# end
#
# Quite straightforward. Make sure to check <tt>ActionController::Base</tt>
# available modules if you want to include any other functionality that is
# not provided by <tt>ActionController::API</tt> out of the box.
class API < Metal
abstract!
module Compatibility
def cache_store; end
def cache_store=(*); end
def assets_dir=(*); end
def javascripts_dir=(*); end
def stylesheets_dir=(*); end
def page_cache_directory=(*); end
def asset_path=(*); end
def asset_host=(*); end
def relative_url_root=(*); end
def perform_caching=(*); end
def helpers_path=(*); end
def allow_forgery_protection=(*); end
def helper_method(*); end
def helper(*); end
end
extend Compatibility
# Shortcut helper that returns all the ActionController::API modules except the ones passed in the argument:
#
# class MetalController
# ActionController::API.without_modules(:Redirecting, :DataStreaming).each do |left|
# include left
# end
# end
#
# This gives better control over what you want to exclude and makes it easier
# to create an api controller class, instead of listing the modules required manually.
def self.without_modules(*modules)
modules = modules.map do |m|
m.is_a?(Symbol) ? ActionController.const_get(m) : m
end
MODULES - modules
end
MODULES = [
UrlFor,
Redirecting,
Rendering,
Renderers::All,
ConditionalGet,
RackDelegation,
ForceSSL,
DataStreaming,
# Before callbacks should also be executed the earliest as possible, so
# also include them at the bottom.
AbstractController::Callbacks,
# Append rescue at the bottom to wrap as much as possible.
Rescue,
# Add instrumentations hooks at the bottom, to ensure they instrument
# all the methods properly.
Instrumentation
].freeze
if Rails::VERSION::MAJOR == 5 || (Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR > 0)
include AbstractController::Rendering
include ActionView::Rendering
end
if Rails::VERSION::MAJOR < 5
include ActionController::HideActions
end
MODULES.each do |mod|
include mod
end
DEFAULT_PROTECTED_INSTANCE_VARIABLES = begin
if Rails::VERSION::MAJOR == 5 || (Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR > 0)
Set
else
Array
end
end.new
def self.protected_instance_variables
DEFAULT_PROTECTED_INSTANCE_VARIABLES
end
if Rails::VERSION::MAJOR >= 4
include StrongParameters
end
ActiveSupport.run_load_hooks(:action_controller, self)
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
rails-api/rails-api | https://github.com/rails-api/rails-api/blob/91c6c35a3babfcec535e7e2469eca8aa49289b4a/lib/generators/rails/api_resource_route/api_resource_route_generator.rb | lib/generators/rails/api_resource_route/api_resource_route_generator.rb | require 'rails/generators/rails/resource_route/resource_route_generator'
module Rails
module Generators
class ApiResourceRouteGenerator < ResourceRouteGenerator
def add_resource_route
return if options[:actions].present?
route_config = regular_class_path.collect{ |namespace| "namespace :#{namespace} do " }.join(" ")
route_config << "resources :#{file_name.pluralize}"
route_config << ", except: [:new, :edit]"
route_config << " end" * regular_class_path.size
route route_config
end
end
end
end
| ruby | MIT | 91c6c35a3babfcec535e7e2469eca8aa49289b4a | 2026-01-04T15:44:04.272150Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/action_class_finder_spec.rb | spec/action_class_finder_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
require 'formtastic/action_class_finder'
RSpec.describe Formtastic::ActionClassFinder do
include FormtasticSpecHelper
it_behaves_like 'Specialized Class Finder' do
let(:default) { Formtastic::Actions }
let(:namespaces_setting) { :action_namespaces }
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/namespaced_class_finder_spec.rb | spec/namespaced_class_finder_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
require 'formtastic/namespaced_class_finder'
RSpec.describe Formtastic::NamespacedClassFinder do
include FormtasticSpecHelper
before do
stub_const('SearchPath', Module.new)
end
let(:search_path) { [ SearchPath ] }
subject(:finder) { Formtastic::NamespacedClassFinder.new(search_path) }
shared_examples 'Namespaced Class Finder' do
subject(:found_class) { finder.find(:custom_class) }
context 'Input defined in the Object scope' do
before do
stub_const('CustomClass', Class.new)
end
it { expect(found_class).to be(CustomClass) }
end
context 'Input defined in the search path' do
before do
stub_const('SearchPath::CustomClass', Class.new)
end
it { expect(found_class).to be(SearchPath::CustomClass) }
end
context 'Input defined both in the Object scope and the search path' do
before do
stub_const('CustomClass', Class.new)
stub_const('SearchPath::CustomClass', Class.new)
end
it { expect(found_class).to be(SearchPath::CustomClass) }
end
context 'Input defined outside the search path' do
before do
stub_const('Foo', Module.new)
stub_const('Foo::CustomClass', Class.new)
end
let(:error) { Formtastic::NamespacedClassFinder::NotFoundError }
it { expect { found_class }.to raise_error(error) }
end
end
context '#finder' do
before do
allow(Rails.application.config).to receive(:eager_load).and_return(eager_load)
end
context 'when eager_load is on' do
let(:eager_load) { true }
it "finder_method is :find_with_const_defined" do
expect(described_class.finder_method).to eq(:find_with_const_defined)
end
it_behaves_like 'Namespaced Class Finder'
end
context 'when eager_load is off' do
let(:eager_load) { false }
it "finder_method is :find_by_trying" do
described_class.instance_variable_set(:@finder_method, nil) # clear cache
expect(described_class.finder_method).to eq(:find_by_trying)
end
it_behaves_like 'Namespaced Class Finder'
end
end
context '#find' do
it 'caches calls' do
expect(subject).to receive(:resolve).once.and_call_original
subject.find(:object)
subject.find(:object)
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/localizer_spec.rb | spec/localizer_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::Localizer' do
describe "Cache" do
before do
@cache = Formtastic::Localizer::Cache.new
@key = ['model', 'name']
@undefined_key = ['model', 'undefined']
@cache.set(@key, 'value')
end
it "should get value" do
expect(@cache.get(@key)).to eq('value')
expect(@cache.get(@undefined_key)).to be_nil
end
it "should check if key exists?" do
expect(@cache.has_key?(@key)).to be_truthy
expect(@cache.has_key?(@undefined_key)).to be_falsey
end
it "should set a key" do
@cache.set(['model', 'name2'], 'value2')
expect(@cache.get(['model', 'name2'])).to eq('value2')
end
it "should return hash" do
expect(@cache.cache).to be_an_instance_of(Hash)
end
it "should clear the cache" do
@cache.clear!
expect(@cache.get(@key)).to be_nil
end
end
describe "Localizer" do
include FormtasticSpecHelper
before do
mock_everything
with_config :i18n_lookups_by_default, true do
semantic_form_for(@new_post) do |builder|
@localizer = Formtastic::Localizer.new(builder)
end
end
end
after do
::I18n.backend.reload!
end
it "should be defined" do
expect { Formtastic::Localizer }.not_to raise_error
end
it "should have a cache" do
expect(Formtastic::Localizer.cache).to be_an_instance_of(Formtastic::Localizer::Cache)
end
describe "localize" do
def store_post_translations(value)
::I18n.backend.store_translations :en, {:formtastic => {
:labels => {
:post => { :name => value }
}
}
}
end
before do
store_post_translations('POST.NAME')
end
it "should translate key with i18n" do
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NAME')
end
describe "with caching" do
it "should not update translation when stored translations change" do
with_config :i18n_cache_lookups, true do
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NAME')
store_post_translations('POST.NEW_NAME')
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NAME')
Formtastic::Localizer.cache.clear!
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NEW_NAME')
end
end
end
describe "without caching" do
it "should update translation when stored translations change" do
with_config :i18n_cache_lookups, false do
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NAME')
store_post_translations('POST.NEW_NAME')
expect(@localizer.localize(:name, :name, :label)).to eq('POST.NEW_NAME')
end
end
end
describe "with custom resource name" do
before do
::I18n.backend.store_translations :en, {:formtastic => {
:labels => {
:post => { :name => 'POST.NAME' },
:message => { :name => 'MESSAGE.NAME' }
}
}
}
with_config :i18n_lookups_by_default, true do
semantic_form_for(@new_post, :as => :message) do |builder|
@localizer = Formtastic::Localizer.new(builder)
end
end
end
it "should translate custom key with i18n" do
expect(@localizer.localize(:name, :name, :label)).to eq('MESSAGE.NAME')
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/input_class_finder_spec.rb | spec/input_class_finder_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
require 'formtastic/input_class_finder'
RSpec.describe Formtastic::InputClassFinder do
it_behaves_like 'Specialized Class Finder' do
let(:default) { Formtastic::Inputs }
let(:namespaces_setting) { :input_namespaces }
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/i18n_spec.rb | spec/i18n_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::I18n' do
FORMTASTIC_KEYS = [:required, :yes, :no, :create, :update].freeze
it "should be defined" do
expect { Formtastic::I18n }.not_to raise_error
end
describe "default translations" do
it "should be defined" do
expect { Formtastic::I18n::DEFAULT_VALUES }.not_to raise_error
expect(Formtastic::I18n::DEFAULT_VALUES.is_a?(::Hash)).to eq(true)
end
it "should exists for the core I18n lookup keys" do
expect((Formtastic::I18n::DEFAULT_VALUES.keys & FORMTASTIC_KEYS).size).to eq(FORMTASTIC_KEYS.size)
end
end
describe "when I18n locales are available" do
before do
@formtastic_strings = {
:yes => 'Default Yes',
:no => 'Default No',
:create => 'Default Create %{model}',
:update => 'Default Update %{model}',
:custom_scope => {
:duck => 'Duck',
:duck_pond => '%{ducks} ducks in a pond'
}
}
::I18n.backend.store_translations :en, :formtastic => @formtastic_strings
end
after do
::I18n.backend.reload!
end
it "should translate core strings correctly" do
::I18n.backend.store_translations :en, {:formtastic => {:required => 'Default Required'}}
expect(Formtastic::I18n.t(:required)).to eq("Default Required")
expect(Formtastic::I18n.t(:yes)).to eq("Default Yes")
expect(Formtastic::I18n.t(:no)).to eq("Default No")
expect(Formtastic::I18n.t(:create, :model => 'Post')).to eq("Default Create Post")
expect(Formtastic::I18n.t(:update, :model => 'Post')).to eq("Default Update Post")
end
it "should all belong to scope 'formtastic'" do
expect(Formtastic::I18n.t(:duck, :scope => [:custom_scope])).to eq('Duck')
end
it "should override default I18n lookup args if these are specified" do
expect(Formtastic::I18n.t(:duck_pond, :scope => [:custom_scope], :ducks => 15)).to eq('15 ducks in a pond')
end
it "should be possible to override default values" do
expect(Formtastic::I18n.t(:required, :default => 'Nothing found!')).to eq('Nothing found!')
end
end
describe "when no I18n locales are available" do
before do
::I18n.backend.reload!
end
it "should use default strings" do
(Formtastic::I18n::DEFAULT_VALUES.keys).each do |key|
expect(Formtastic::I18n.t(key, :model => '%{model}')).to eq(Formtastic::I18n::DEFAULT_VALUES[key])
end
end
end
describe "I18n string lookups" do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
::I18n.backend.store_translations :en, {:formtastic => {
:labels => {
:author => { :name => "Top author name transation" },
:post => {:title => "Hello post!", :author => {:name => "Hello author name!"}},
:project => {:title => "Hello project!"},
}
}, :helpers => {
:label => {
:post => {:body => "Elaborate..." },
:author => { :login => "Hello login" }
}
}}
allow(@new_post).to receive(:title)
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :string, :limit => 255))
end
after do
::I18n.backend.reload!
end
it "lookup scopes should be defined" do
with_config :i18n_lookups_by_default, true do
expect { Formtastic::I18n::SCOPES }.not_to raise_error
end
end
it "should be able to translate with namespaced object" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello post!/)
end
end
it "should be able to translate without form-object" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello project!/)
end
end
it "should be able to translate when method name is same as model" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author))
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Author/)
end
end
it 'should be able to translate nested objects with nested translations' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.semantic_fields_for(:author) do |f|
concat(f.input(:name))
end)
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello author name!/)
end
end
it 'should be able to translate nested objects with top level translations' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(:author) do |f|
concat(f.input(:name))
end
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello author name!/)
end
end
it 'should be able to translate nested objects with nested object translations' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(:project) do |f|
concat(f.input(:title))
end
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello project!/)
end
end
it 'should be able to translate nested forms with top level translations' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(:post) do |builder|
builder.semantic_fields_for(:author) do |f|
concat(f.input(:name))
end
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello author name!/)
end
end
it 'should be able to translate helper label as Rails does' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:body))
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Elaborate/)
end
end
it 'should be able to translate nested helper label as Rails does' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs(:for => :author) do |f|
concat(f.input(:login))
end)
end)
expect(output_buffer.to_str).to have_tag("form label", :text => /Hello login/)
end
end
# TODO: Add spec for namespaced models?
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/fast_spec_helper.rb | spec/fast_spec_helper.rb | # encoding: utf-8
# frozen_string_literal: true
$LOAD_PATH << 'lib/formtastic'
require 'active_support/all'
require 'localized_string'
require 'inputs'
require 'helpers'
class MyInput
include Formtastic::Inputs::Base
end
I18n.enforce_available_locales = false if I18n.respond_to?(:enforce_available_locales)
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/schema.rb | spec/schema.rb | # frozen_string_literal: true
ActiveRecord::Schema.define(version: 20170208011723) do
create_table "posts", force: :cascade do |t|
t.integer "author_id", limit: 4, null: false
end
create_table "authors", force: :cascade do |t|
t.integer "age", limit: 4, null: false
t.string "name", limit: 255, null: false
t.string "surname", limit: 255, null: false
t.string "login", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
#non-rails foreign id convention
create_table "legacy_posts", force: :cascade do |t|
t.integer "post_author", limit: 4, null: false
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/spec_helper.rb | spec/spec_helper.rb | # encoding: utf-8
# frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
require 'active_support'
require 'action_pack'
require 'action_view'
require 'action_controller'
require 'action_dispatch'
require 'active_record'
ActiveRecord::Base.establish_connection('url' => 'sqlite3::memory:', 'pool' => 1)
load 'spec/schema.rb'
require File.expand_path(File.join(File.dirname(__FILE__), '../lib/formtastic'))
require 'ammeter/init'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories in alphabetic order.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each {|f| require f}
I18n.enforce_available_locales = false if I18n.respond_to?(:enforce_available_locales)
module FakeHelpersModule
end
module FormtasticSpecHelper
include ActionPack
include ActionView::Context if defined?(ActionView::Context)
include ActionController::RecordIdentifier if defined?(ActionController::RecordIdentifier)
include ActionView::Helpers::FormHelper
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::FormOptionsHelper
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
include ActionView::Helpers::ActiveRecordHelper if defined?(ActionView::Helpers::ActiveRecordHelper)
include ActionView::Helpers::ActiveModelHelper if defined?(ActionView::Helpers::ActiveModelHelper)
include ActionView::Helpers::DateHelper
include ActionView::Helpers::CaptureHelper
include ActionView::Helpers::AssetTagHelper
include ActiveSupport
include ActionController::PolymorphicRoutes if defined?(ActionController::PolymorphicRoutes)
include ActionDispatch::Routing::PolymorphicRoutes
include AbstractController::UrlFor if defined?(AbstractController::UrlFor)
include ActionView::RecordIdentifier if defined?(ActionView::RecordIdentifier)
include Formtastic::Helpers::FormHelper
def default_input_type(column_type, column_name = :generic_column_name)
allow(@new_post).to receive(column_name)
allow(@new_post).to receive(:column_for_attribute).and_return(double('column', :type => column_type)) unless column_type.nil?
semantic_form_for(@new_post) do |builder|
@default_type = builder.send(:default_input_type, column_name)
end
return @default_type
end
def active_model_validator(kind, attributes, options = {})
validator = double("ActiveModel::Validations::#{kind.to_s.titlecase}Validator", :attributes => attributes, :options => options)
allow(validator).to receive(:kind).and_return(kind)
validator
end
def active_model_presence_validator(attributes, options = {})
active_model_validator(:presence, attributes, options)
end
def active_model_length_validator(attributes, options = {})
active_model_validator(:length, attributes, options)
end
def active_model_inclusion_validator(attributes, options = {})
active_model_validator(:inclusion, attributes, options)
end
def active_model_numericality_validator(attributes, options = {})
active_model_validator(:numericality, attributes, options)
end
class ::MongoPost
include MongoMapper::Document if defined?(MongoMapper::Document)
def id
end
def persisted?
end
end
class ::Post
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
def id
end
def persisted?
end
end
module ::Namespaced
class Post < ActiveRecord::Base
end
end
class ::Author < ActiveRecord::Base
def new_record?
!id
end
def to_label
[name, surname].compact.join(' ')
end
end
class ::HashBackedAuthor < Hash
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
def persisted?; false; end
def name
'hash backed author'
end
end
class ::LegacyPost < ActiveRecord::Base
belongs_to :author, foreign_key: :post_author
end
class ::Continent
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
end
class ::PostModel
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
end
##
# We can't mock :respond_to?, so we need a concrete class override
class ::MongoidReflectionMock < RSpec::Mocks::Double
def initialize(name=nil, stubs_and_options={})
super name, stubs_and_options
end
def respond_to?(sym)
sym == :options ? false : super
end
end
# Model.all returns an association proxy, which quacks a lot like an array.
# We use this in stubs or mocks where we need to return the later.
#
# TODO try delegate?
# delegate :map, :size, :length, :first, :to_ary, :each, :include?, :to => :array
class MockScope
attr_reader :array
def initialize(the_array)
@array = the_array
end
def map(&block)
array.map(&block)
end
def where(*args)
# array
self
end
def includes(*args)
self
end
def size
array.size
end
alias_method :length, :size
def first
array.first
end
def to_ary
array
end
def each(&block)
array.each(&block)
end
def include?(*args)
array.include?(*args)
end
end
def _routes
url_helpers = double('url_helpers')
allow(url_helpers).to receive(:hash_for_posts_path).and_return({})
allow(url_helpers).to receive(:hash_for_post_path).and_return({})
allow(url_helpers).to receive(:hash_for_post_models_path).and_return({})
allow(url_helpers).to receive(:hash_for_authors_path).and_return({})
double('_routes',
:url_helpers => url_helpers,
:url_for => "/mock/path",
:polymorphic_mappings => {}
)
end
def controller
env = double('env', :[] => nil)
request = double('request', :env => env)
double('controller', :controller_path= => '', :params => {}, :request => request)
end
def default_url_options
{}
end
def mock_everything
# Resource-oriented styles like form_for(@post) will expect a path method for the object,
# so we're defining some here.
def post_models_path(*args); "/postmodels/1"; end
def post_path(*args); "/posts/1"; end
def posts_path(*args); "/posts"; end
def new_post_path(*args); "/posts/new"; end
def author_path(*args); "/authors/1"; end
def authors_path(*args); "/authors"; end
def new_author_path(*args); "/authors/new"; end
def author_array_or_scope(the_array = [@fred, @bob])
MockScope.new(the_array)
end
@fred = ::Author.new(login: 'fred_smith', age: 27, name: 'Fred', id: 37)
@bob = ::Author.new(login: 'bob', age: 43, name: 'Bob', id: 42)
@james = ::Author.new(age: 38, id: 75)
allow(::Author).to receive(:scoped).and_return(::Author)
allow(::Author).to receive(:find).and_return(author_array_or_scope)
allow(::Author).to receive(:all).and_return(author_array_or_scope)
allow(::Author).to receive(:where).and_return(author_array_or_scope)
allow(::Author).to receive(:human_attribute_name) { |column_name| column_name.humanize }
allow(::Author).to receive(:human_name).and_return('::Author')
allow(::Author).to receive(:reflect_on_association) { |column_name| double('reflection', :scope => nil, :options => {}, :klass => Post, :macro => :has_many) if column_name == :posts }
allow(::Author).to receive(:content_columns).and_return([double('column', :name => 'login'), double('column', :name => 'created_at')])
allow(::Author).to receive(:to_key).and_return(nil)
allow(::Author).to receive(:persisted?).and_return(nil)
@hash_backed_author = HashBackedAuthor.new
# Sometimes we need a mock @post object and some Authors for belongs_to
@new_post = double('post')
allow(@new_post).to receive(:class).and_return(::Post)
allow(@new_post).to receive(:id).and_return(nil)
allow(@new_post).to receive(:new_record?).and_return(true)
allow(@new_post).to receive(:errors).and_return(double('errors', :[] => nil))
allow(@new_post).to receive(:author).and_return(nil)
allow(@new_post).to receive(:author_attributes=).and_return(nil)
allow(@new_post).to receive(:authors).and_return(author_array_or_scope([@fred]))
allow(@new_post).to receive(:authors_attributes=)
allow(@new_post).to receive(:reviewer).and_return(nil)
allow(@new_post).to receive(:main_post).and_return(nil)
allow(@new_post).to receive(:sub_posts).and_return([]) #TODO should be a mock with methods for adding sub posts
allow(@new_post).to receive(:to_key).and_return(nil)
allow(@new_post).to receive(:to_model).and_return(@new_post)
allow(@new_post).to receive(:persisted?).and_return(nil)
allow(@new_post).to receive(:model_name){ @new_post.class.model_name}
@freds_post = double('post')
allow(@freds_post).to receive(:to_ary)
allow(@freds_post).to receive(:class).and_return(::Post)
allow(@freds_post).to receive(:to_label).and_return('Fred Smith')
allow(@freds_post).to receive(:id).and_return(19)
allow(@freds_post).to receive(:title).and_return("Hello World")
allow(@freds_post).to receive(:author).and_return(@fred)
allow(@freds_post).to receive(:author_id).and_return(@fred.id)
allow(@freds_post).to receive(:authors).and_return([@fred])
allow(@freds_post).to receive(:author_ids).and_return([@fred.id])
allow(@freds_post).to receive(:new_record?).and_return(false)
allow(@freds_post).to receive(:errors).and_return(double('errors', :[] => nil))
allow(@freds_post).to receive(:to_key).and_return(nil)
allow(@freds_post).to receive(:persisted?).and_return(nil)
allow(@freds_post).to receive(:model_name){ @freds_post.class.model_name}
allow(@freds_post).to receive(:to_model).and_return(@freds_post)
allow(@fred).to receive(:posts).and_return(author_array_or_scope([@freds_post]))
allow(@fred).to receive(:post_ids).and_return([@freds_post.id])
allow(::Post).to receive(:scoped).and_return(::Post)
allow(::Post).to receive(:human_attribute_name) { |column_name| column_name.humanize }
allow(::Post).to receive(:human_name).and_return('Post')
allow(::Post).to receive(:reflect_on_all_validations).and_return([])
allow(::Post).to receive(:reflect_on_validations_for).and_return([])
allow(::Post).to receive(:reflections).and_return({})
allow(::Post).to receive(:reflect_on_association) { |column_name|
case column_name
when :author, :author_status
mock = double('reflection', :scope => nil, :options => {}, :klass => ::Author, :macro => :belongs_to)
allow(mock).to receive(:[]).with(:class_name).and_return("Author")
mock
when :reviewer
mock = double('reflection', :scope => nil, :options => {:class_name => 'Author'}, :klass => ::Author, :macro => :belongs_to)
allow(mock).to receive(:[]).with(:class_name).and_return("Author")
mock
when :authors
double('reflection', :scope => nil, :options => {}, :klass => ::Author, :macro => :has_and_belongs_to_many)
when :sub_posts
double('reflection', :scope => nil, :options => {}, :klass => ::Post, :macro => :has_many)
when :main_post
double('reflection', :scope => nil, :options => {}, :klass => ::Post, :macro => :belongs_to)
when :mongoid_reviewer
::MongoidReflectionMock.new('reflection',
:scope => nil,
:options => Proc.new { raise NoMethodError, "Mongoid has no reflection.options" },
:klass => ::Author, :macro => :referenced_in, :foreign_key => "reviewer_id") # custom id
end
}
allow(::Post).to receive(:find).and_return(author_array_or_scope([@freds_post]))
allow(::Post).to receive(:all).and_return(author_array_or_scope([@freds_post]))
allow(::Post).to receive(:where).and_return(author_array_or_scope([@freds_post]))
allow(::Post).to receive(:content_columns).and_return([double('column', :name => 'title'), double('column', :name => 'body'), double('column', :name => 'created_at')])
allow(::Post).to receive(:to_key).and_return(nil)
allow(::Post).to receive(:persisted?).and_return(nil)
allow(::Post).to receive(:to_ary)
allow(::MongoPost).to receive(:human_attribute_name) { |column_name| column_name.humanize }
allow(::MongoPost).to receive(:human_name).and_return('MongoPost')
allow(::MongoPost).to receive(:associations).and_return({
:sub_posts => double('reflection', :options => {:polymorphic => true}, :klass => ::MongoPost, :macro => :has_many),
:options => []
})
allow(::MongoPost).to receive(:find).and_return(author_array_or_scope([@freds_post]))
allow(::MongoPost).to receive(:all).and_return(author_array_or_scope([@freds_post]))
allow(::MongoPost).to receive(:where).and_return(author_array_or_scope([@freds_post]))
allow(::MongoPost).to receive(:to_key).and_return(nil)
allow(::MongoPost).to receive(:persisted?).and_return(nil)
allow(::MongoPost).to receive(:to_ary)
allow(::MongoPost).to receive(:model_name).and_return( double(:model_name_mock, :singular => "post", :plural => "posts", :param_key => "post", :route_key => "posts", :name => "post") )
@new_mm_post = double('mm_post')
allow(@new_mm_post).to receive(:class).and_return(::MongoPost)
allow(@new_mm_post).to receive(:id).and_return(nil)
allow(@new_mm_post).to receive(:new_record?).and_return(true)
allow(@new_mm_post).to receive(:errors).and_return(double('errors', :[] => nil))
allow(@new_mm_post).to receive(:title).and_return("Hello World")
allow(@new_mm_post).to receive(:sub_posts).and_return([]) #TODO should be a mock with methods for adding sub posts
allow(@new_mm_post).to receive(:to_key).and_return(nil)
allow(@new_mm_post).to receive(:to_model).and_return(@new_mm_post)
allow(@new_mm_post).to receive(:persisted?).and_return(nil)
allow(@new_mm_post).to receive(:model_name).and_return(::MongoPost.model_name)
@mock_file = double('file')
Formtastic::FormBuilder.file_methods.each do |method|
allow(@mock_file).to receive(method).and_return(true)
end
allow(@new_post).to receive(:title)
allow(@new_post).to receive(:status)
allow(@new_post).to receive(:email)
allow(@new_post).to receive(:url)
allow(@new_post).to receive(:phone)
allow(@new_post).to receive(:search)
allow(@new_post).to receive(:to_ary)
allow(@new_post).to receive(:body)
allow(@new_post).to receive(:published)
allow(@new_post).to receive(:publish_at)
allow(@new_post).to receive(:created_at)
allow(@new_post).to receive(:secret).and_return(1)
allow(@new_post).to receive(:url)
allow(@new_post).to receive(:email)
allow(@new_post).to receive(:color)
allow(@new_post).to receive(:search)
allow(@new_post).to receive(:phone)
allow(@new_post).to receive(:time_zone)
allow(@new_post).to receive(:category_name)
allow(@new_post).to receive(:allow_comments).and_return(true)
allow(@new_post).to receive(:answer_comments)
allow(@new_post).to receive(:country)
allow(@new_post).to receive(:country_subdivision)
allow(@new_post).to receive(:country_code)
allow(@new_post).to receive(:document).and_return(@mock_file)
allow(@new_post).to receive(:column_for_attribute).with(:meta_description).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :string, :limit => 50))
allow(@new_post).to receive(:column_for_attribute).with(:status).and_return(double('column', :type => :integer, :limit => 1))
allow(@new_post).to receive(:column_for_attribute).with(:body).and_return(double('column', :type => :text))
allow(@new_post).to receive(:column_for_attribute).with(:published).and_return(double('column', :type => :boolean))
allow(@new_post).to receive(:column_for_attribute).with(:publish_at).and_return(double('column', :type => :date))
allow(@new_post).to receive(:column_for_attribute).with(:time_zone).and_return(double('column', :type => :string))
allow(@new_post).to receive(:column_for_attribute).with(:allow_comments).and_return(double('column', :type => :boolean))
allow(@new_post).to receive(:column_for_attribute).with(:author).and_return(double('column', :type => :integer))
allow(@new_post).to receive(:column_for_attribute).with(:country).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:country_subdivision).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:country_code).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:email).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:color).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:url).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:phone).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:search).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:document).and_return(nil)
allow(@new_post).to receive(:author).and_return(@bob)
allow(@new_post).to receive(:author_id).and_return(@bob.id)
allow(@new_post).to receive(:reviewer).and_return(@fred)
allow(@new_post).to receive(:reviewer_id).and_return(@fred.id)
# @new_post.should_receive(:publish_at=).at_least(:once)
allow(@new_post).to receive(:publish_at=)
# @new_post.should_receive(:title=).at_least(:once)
allow(@new_post).to receive(:title=)
allow(@new_post).to receive(:main_post_id).and_return(nil)
end
def self.included(base)
base.class_eval do
attr_accessor :output_buffer
def protect_against_forgery?
false
end
def _helpers
FakeHelpersModule
end
end
end
def with_config(config_method_name, value, &block)
old_value = Formtastic::FormBuilder.send(config_method_name)
Formtastic::FormBuilder.send(:"#{config_method_name}=", value)
yield
Formtastic::FormBuilder.send(:"#{config_method_name}=", old_value)
end
RSpec::Matchers.define :errors_matcher do |expected|
match { |actual| actual.to_s == expected.to_s }
end
end
class ::ActionView::Base
include Formtastic::Helpers::FormHelper
end
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
config.filter_run focus: true
config.filter_run_excluding skip: true
config.run_all_when_everything_filtered = true
config.before(:example) do
Formtastic::Localizer.cache.clear!
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/support/custom_macros.rb | spec/support/custom_macros.rb | # encoding: utf-8
# frozen_string_literal: true
module CustomMacros
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def it_should_have_input_wrapper_with_class(class_name)
it "should have input wrapper with class '#{class_name}'" do
expect(output_buffer.to_str).to have_tag("form li.#{class_name}")
end
end
def it_should_have_input_wrapper_with_id(id_string)
it "should have input wrapper with id '#{id_string}'" do
expect(output_buffer.to_str).to have_tag("form li##{id_string}")
end
end
def it_should_not_have_a_label
it "should not have a label" do
expect(output_buffer.to_str).not_to have_tag("form li label")
end
end
def it_should_have_a_nested_fieldset
it "should have a nested_fieldset" do
expect(output_buffer.to_str).to have_tag("form li fieldset")
end
end
def it_should_have_a_nested_fieldset_with_class(klass)
it "should have a nested_fieldset with class #{klass}" do
expect(output_buffer.to_str).to have_tag("form li fieldset.#{klass}")
end
end
def it_should_have_a_nested_ordered_list_with_class(klass)
it "should have a nested fieldset with class #{klass}" do
expect(output_buffer.to_str).to have_tag("form li ol.#{klass}")
end
end
def it_should_have_label_with_text(string_or_regex)
it "should have a label with text '#{string_or_regex}'" do
expect(output_buffer.to_str).to have_tag("form li label", :text => string_or_regex)
end
end
def it_should_have_label_for(element_id)
it "should have a label for ##{element_id}" do
expect(output_buffer.to_str).to have_tag("form li label.label[@for='#{element_id}']")
end
end
def it_should_have_an_inline_label_for(element_id)
it "should have a label for ##{element_id}" do
expect(output_buffer.to_str).to have_tag("form li label[@for='#{element_id}']")
end
end
def it_should_have_input_with_id(element_id)
it "should have an input with id '#{element_id}'" do
expect(output_buffer.to_str).to have_tag("form li input##{element_id}")
end
end
def it_should_have_select_with_id(element_id)
it "should have a select box with id '#{element_id}'" do
expect(output_buffer.to_str).to have_tag("form li select##{element_id}")
end
end
# TODO use for many of the other macros
def it_should_have_tag_with(type, attribute_value_hash)
attribute_value_hash.each do |attribute, value|
it "should have a #{type} box with #{attribute} '#{value}'" do
expect(output_buffer.to_str).to have_tag("form li #{type}[@#{attribute}=\"#{value}\"]")
end
end
end
def it_should_have_input_with(attribute_value_hash)
it_should_have_tag_with(:input, attribute_value_hash)
end
def it_should_have_many_tags(type, count)
it "should have #{count} #{type} tags" do
expect(output_buffer.to_str).to have_tag("form li #{type}", count: count)
end
end
def it_should_have_input_with_type(input_type)
it "should have a #{input_type} input" do
expect(output_buffer.to_str).to have_tag("form li input[@type=\"#{input_type}\"]")
end
end
def it_should_have_input_with_name(name)
it "should have an input named #{name}" do
expect(output_buffer.to_str).to have_tag("form li input[@name=\"#{name}\"]")
end
end
def it_should_have_select_with_name(name)
it "should have an input named #{name}" do
expect(output_buffer.to_str).to have_tag("form li select[@name=\"#{name}\"]")
end
end
def it_should_have_textarea_with_name(name)
it "should have an input named #{name}" do
expect(output_buffer.to_str).to have_tag("form li textarea[@name=\"#{name}\"]")
end
end
def it_should_have_textarea_with_id(element_id)
it "should have an input with id '#{element_id}'" do
expect(output_buffer.to_str).to have_tag("form li textarea##{element_id}")
end
end
def it_should_have_label_and_input_with_id(element_id)
it "should have an input with id '#{element_id}'" do
expect(output_buffer.to_str).to have_tag("form li input##{element_id}")
expect(output_buffer.to_str).to have_tag("form li label[@for='#{element_id}']")
end
end
def it_should_use_default_text_field_size_when_not_nil(as)
it 'should use default_text_field_size when not nil' do
with_config :default_text_field_size, 30 do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => as))
end)
expect(output_buffer.to_str).to have_tag("form li input[@size='#{Formtastic::FormBuilder.default_text_field_size}']")
end
end
end
def it_should_not_use_default_text_field_size_when_nil(as)
it 'should not use default_text_field_size when nil' do
with_config :default_text_field_size, nil do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => as))
end)
expect(output_buffer.to_str).to have_tag("form li input")
expect(output_buffer.to_str).not_to have_tag("form li input[@size]")
end
end
end
def it_should_apply_custom_input_attributes_when_input_html_provided(as)
it 'it should apply custom input attributes when input_html provided' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => as, :input_html => { :class => 'myclass' }))
end)
expect(output_buffer.to_str).to have_tag("form li input.myclass")
end
end
def it_should_apply_custom_for_to_label_when_input_html_id_provided(as)
it 'it should apply custom for to label when input_html :id provided' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => as, :input_html => { :id => 'myid' }))
end)
expect(output_buffer.to_str).to have_tag('form li label[@for="myid"]')
end
end
def it_should_have_maxlength_matching_string_column_limit
it 'should have a maxlength matching column limit' do
expect(@new_post.column_for_attribute(:title).type).to eq(:string)
expect(@new_post.column_for_attribute(:title).limit).to eq(50)
expect(output_buffer.to_str).to have_tag("form li input[@maxlength='50']")
end
end
def it_should_have_maxlength_matching_integer_column_limit
it 'should have a maxlength matching column limit' do
expect(@new_post.column_for_attribute(:status).type).to eq(:integer)
expect(@new_post.column_for_attribute(:status).limit).to eq(1)
expect(output_buffer.to_str).to have_tag("form li input[@maxlength='3']")
end
end
def it_should_use_column_size_for_columns_shorter_than_default_text_field_size(as)
it 'should use the column size for columns shorter than default_text_field_size' do
column_limit_shorted_than_default = 1
allow(@new_post).to receive(:column_for_attribute)
.and_return(double('column', :type => as, :limit => column_limit_shorted_than_default))
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => as))
end)
expect(output_buffer.to_str).to have_tag("form li input[@size='#{column_limit_shorted_than_default}']")
end
end
def it_should_apply_error_logic_for_input_type(type)
describe 'when there are errors on the object for this method' do
before do
@title_errors = ['must not be blank', 'must be longer than 10 characters', 'must be awesome']
@errors = double('errors')
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return(@title_errors)
Formtastic::FormBuilder.file_metadata_suffixes.each do |suffix|
allow(@errors).to receive(:[]).with(errors_matcher("title_#{suffix}".to_sym)).and_return(nil)
end
allow(@new_post).to receive(:errors).and_return(@errors)
end
it 'should apply an errors class to the list item' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).to have_tag('form li.error')
end
it 'should not wrap the input with the Rails default error wrapping' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).not_to have_tag('div.fieldWithErrors')
end
it 'should render a paragraph for the errors' do
Formtastic::FormBuilder.inline_errors = :sentence
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).to have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
Formtastic::FormBuilder.inline_errors = :list
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).to have_tag('form li.error ul.errors')
end
end
describe 'when there are no errors on the object for this method' do
before do
@form = semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end
end
it 'should not apply an errors class to the list item' do
expect(output_buffer.to_str).not_to have_tag('form li.error')
end
it 'should not render a paragraph for the errors' do
expect(output_buffer.to_str).not_to have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
expect(output_buffer.to_str).not_to have_tag('form li.error ul.errors')
end
end
describe 'when no object is provided' do
before do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:title, :as => type))
end)
end
it 'should not apply an errors class to the list item' do
expect(output_buffer.to_str).not_to have_tag('form li.error')
end
it 'should not render a paragraph for the errors' do
expect(output_buffer.to_str).not_to have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
expect(output_buffer.to_str).not_to have_tag('form li.error ul.errors')
end
end
end
def it_should_call_find_on_association_class_when_no_collection_is_provided(as)
it "should call find on the association class when no collection is provided" do
expect(::Author).to receive(:where)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as))
end)
end
end
def it_should_use_the_collection_when_provided(as, countable)
describe 'when the :collection option is provided' do
before do
@authors = ([::Author.all] * 2).flatten
@output_buffer = ActionView::OutputBuffer.new ''
end
it 'should use the provided collection' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :collection => @authors))
end)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}", :count => @authors.size + (as == :select ? 1 : 0))
end
describe 'and the :collection is an array of strings' do
before do
@categories = [ 'General', 'Design', 'Development', 'Quasi-Serious Inventions' ]
end
it "should use the string as the label text and value for each #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @categories))
end)
@categories.each do |value|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{value}/)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{value}']")
end
end
if as == :radio
it 'should generate a sanitized label for attribute' do
allow(@bob).to receive(:category_name).and_return(@categories)
concat(semantic_form_for(@new_post) do |builder|
fields = builder.semantic_fields_for(@bob) do |bob_builder|
concat(bob_builder.input(:category_name, :as => as, :collection => @categories))
end
concat(fields)
end)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_category_name_general']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_category_name_design']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_category_name_development']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_category_name_quasi-serious_inventions']")
end
end
end
describe 'and the :collection is a hash of strings' do
before do
@categories = { 'General' => 'gen', 'Design' => 'des','Development' => 'dev' }
end
it "should use the key as the label text and the hash value as the value attribute for each #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @categories))
end)
@categories.each do |label, value|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{label}/)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{value}']")
end
end
end
describe 'and the :collection is an array of arrays' do
before do
@categories = { 'General' => 'gen', 'Design' => 'des', 'Development' => 'dev' }.to_a
end
it "should use the first value as the label text and the last value as the value attribute for #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @categories))
end)
@categories.each do |text, value|
label = as == :select ? :option : :label
expect(output_buffer.to_str).to have_tag("form li.#{as} #{label}", :text => /#{text}/i)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{value.to_s}']")
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}#post_category_name_#{value.to_s}") if as == :radio
end
end
end
if as == :radio
describe 'and the :collection is an array of arrays with boolean values' do
before do
@choices = { 'Yeah' => true, 'Nah' => false }.to_a
end
it "should use the first value as the label text and the last value as the value attribute for #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @choices))
end)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}#post_category_name_true")
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}#post_category_name_false")
end
end
end
describe 'and the :collection is an array of symbols' do
before do
@categories = [ :General, :Design, :Development ]
end
it "should use the symbol as the label text and value for each #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @categories))
end)
@categories.each do |value|
label = as == :select ? :option : :label
expect(output_buffer.to_str).to have_tag("form li.#{as} #{label}", :text => /#{value}/i)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{value.to_s}']")
end
end
end
describe 'and the :collection is an OrderedHash of strings' do
before do
@categories = ActiveSupport::OrderedHash.new('General' => 'gen', 'Design' => 'des','Development' => 'dev')
end
it "should use the key as the label text and the hash value as the value attribute for each #{countable}" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => as, :collection => @categories))
end)
@categories.each do |label, value|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{label}/)
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{value}']")
end
end
end
describe 'when the :member_label option is provided' do
describe 'as a symbol' do
before do
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_label => :login))
end)
end
end
it 'should have options with text content from the specified method' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{author.login}/)
end
end
end
describe 'as a proc' do
before do
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_label => Proc.new {|a| a.login.reverse }))
end)
end
end
it 'should have options with the proc applied to each' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{author.login.reverse}/)
end
end
end
describe 'as a method object' do
before do
def reverse_login(a)
a.login.reverse
end
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_label => method(:reverse_login)))
end)
end
end
it 'should have options with the proc applied to each' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /#{author.login.reverse}/)
end
end
end
end
describe 'when the :member_label option is not provided' do
Formtastic::FormBuilder.collection_label_methods.each do |label_method|
describe "when the collection objects respond to #{label_method}" do
before do
allow(@fred).to receive(:respond_to?) { |m| m.to_s == label_method || m.to_s == 'id' }
[@fred, @bob].each { |a| allow(a).to receive(label_method).and_return('The Label Text') }
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as))
end)
end
end
it "should render the options with #{label_method} as the label" do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as}", :text => /The Label Text/)
end
end
end
end
end
describe 'when the :member_value option is provided' do
describe 'as a symbol' do
before do
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_value => :login))
end)
end
end
it 'should have options with values from specified method' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{author.login}']")
end
end
end
describe 'as a proc' do
before do
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_value => Proc.new {|a| a.login.reverse }))
end)
end
end
it 'should have options with the proc applied to each value' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{author.login.reverse}']")
end
end
end
describe 'as a method object' do
before do
def reverse_login(a)
a.login.reverse
end
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => as, :member_value => method(:reverse_login)))
end)
end
end
it 'should have options with the proc applied to each value' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li.#{as} #{countable}[@value='#{author.login.reverse}']")
end
end
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/support/deprecation.rb | spec/support/deprecation.rb | # frozen_string_literal: true
def with_deprecation_silenced(&block)
::Formtastic::Deprecation.silence do
yield
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/support/test_environment.rb | spec/support/test_environment.rb | # encoding: utf-8
# frozen_string_literal: true
require 'rspec/core'
require 'rspec-dom-testing'
RSpec.configure do |config|
config.include CustomMacros
config.include RSpec::Dom::Testing::Matchers
config.mock_with :rspec
# rspec-rails 3 will no longer automatically infer an example group's spec type
# from the file location. You can explicitly opt-in to the feature using this
# config option.
# To explicitly tag specs without using automatic inference, set the `:type`
# metadata manually:
#
# describe ThingsController, :type => :controller do
# # Equivalent to being in spec/controllers
# end
config.infer_spec_type_from_file_location!
# Setting this config option `false` removes rspec-core's monkey patching of the
# top level methods like `describe`, `shared_examples_for` and `shared_context`
# on `main` and `Module`. The methods are always available through the `RSpec`
# module like `RSpec.describe` regardless of this setting.
# For backwards compatibility this defaults to `true`.
#
# https://relishapp.com/rspec/rspec-core/v/3-0/docs/configuration/global-namespace-dsl
config.expose_dsl_globally = false
end
require "action_controller/railtie"
require 'active_model'
# Create a simple rails application for use in testing the viewhelper
module FormtasticTest
class Application < Rails::Application
config.active_support.deprecation = :stderr
config.secret_key_base = "secret"
config.eager_load = false
config.active_support.to_time_preserves_timezone = :zone
end
end
FormtasticTest::Application.initialize!
require 'rspec/rails'
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/support/shared_examples.rb | spec/support/shared_examples.rb | # frozen_string_literal: true
RSpec.shared_context 'form builder' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
after do
::I18n.backend.reload!
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/support/specialized_class_finder_shared_example.rb | spec/support/specialized_class_finder_shared_example.rb | # encoding: utf-8
# frozen_string_literal: true
#
RSpec.shared_examples 'Specialized Class Finder' do
let(:builder) { Formtastic::FormBuilder.allocate }
subject(:finder) { described_class.new(builder) }
context 'by default' do
it 'includes Object and the default namespaces' do
expect(finder.namespaces).to eq([Object, default])
end
end
context 'with namespace configuration set to a custom list of modules' do
before do
stub_const('CustomModule', Module.new)
stub_const('AnotherModule', Module.new)
allow(Formtastic::FormBuilder).to receive(namespaces_setting)
.and_return([ CustomModule, AnotherModule ])
end
it 'includes just the custom namespaces' do
expect(finder.namespaces).to eq([CustomModule, AnotherModule])
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/builder/custom_builder_spec.rb | spec/builder/custom_builder_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::Helpers::FormHelper.builder' do
include FormtasticSpecHelper
class MyCustomFormBuilder < Formtastic::FormBuilder
end
# TODO should be a separate spec for custom inputs
class Formtastic::Inputs::AwesomeInput
include Formtastic::Inputs::Base
def to_html
"Awesome!"
end
end
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'is the Formtastic::FormBuilder by default' do
expect(Formtastic::Helpers::FormHelper.builder).to eq(Formtastic::FormBuilder)
end
it 'can be configured to use your own custom form builder' do
# Set it to a custom builder class
Formtastic::Helpers::FormHelper.builder = MyCustomFormBuilder
expect(Formtastic::Helpers::FormHelper.builder).to eq(MyCustomFormBuilder)
# Reset it to the default
Formtastic::Helpers::FormHelper.builder = Formtastic::FormBuilder
expect(Formtastic::Helpers::FormHelper.builder).to eq(Formtastic::FormBuilder)
end
it 'should allow custom settings per form builder subclass' do
with_config(:all_fields_required_by_default, true) do
MyCustomFormBuilder.all_fields_required_by_default = false
expect(MyCustomFormBuilder.all_fields_required_by_default).to be_falsey
expect(Formtastic::FormBuilder.all_fields_required_by_default).to be_truthy
end
end
describe "when using a custom builder" do
before do
allow(@new_post).to receive(:title)
Formtastic::Helpers::FormHelper.builder = MyCustomFormBuilder
end
after do
Formtastic::Helpers::FormHelper.builder = Formtastic::FormBuilder
end
describe "semantic_form_for" do
it "should yield an instance of the custom builder" do
semantic_form_for(@new_post) do |builder|
expect(builder.class).to be(MyCustomFormBuilder)
end
end
# TODO should be a separate spec for custom inputs
it "should allow me to call my custom input" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :awesome))
end
end
# See: https://github.com/formtastic/formtastic/issues/657
it "should not conflict with navigasmic" do
allow_any_instance_of(self.class).to receive(:builder).and_return('navigasmic')
expect { semantic_form_for(@new_post) { |f| } }.not_to raise_error
end
it "should use the custom builder's skipped_columns config for inputs" do
class AnotherCustomFormBuilder < Formtastic::FormBuilder
configure :skipped_columns, [:title, :created_at]
end
#AnotherCustomFormBuilder.skipped_columns = [:title, :created_at]
concat(semantic_form_for(@new_post, builder: AnotherCustomFormBuilder) do |builder|
concat(builder.inputs)
end)
expect(output_buffer.to_str).to_not have_tag('input#post_title')
expect(output_buffer.to_str).to_not have_tag('li#post_created_at_input')
expect(output_buffer.to_str).to have_tag('textarea#post_body')
end
end
describe "fields_for" do
it "should yield an instance of the parent form builder" do
allow(@new_post).to receive(:comment).and_return([@fred])
allow(@new_post).to receive(:comment_attributes=)
semantic_form_for(@new_post, :builder => MyCustomFormBuilder) do |builder|
expect(builder.class).to be(MyCustomFormBuilder)
builder.fields_for(:comment) do |nested_builder|
expect(nested_builder.class).to be(MyCustomFormBuilder)
end
end
end
end
end
describe "when using a builder passed to form options" do
describe "fields_for" do
it "should yield an instance of the parent form builder" do
allow(@new_post).to receive(:author_attributes=)
semantic_form_for(@new_post, :builder => MyCustomFormBuilder) do |builder|
builder.fields_for(:author) do |nested_builder|
expect(nested_builder.class).to be(MyCustomFormBuilder)
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/builder/semantic_fields_for_spec.rb | spec/builder/semantic_fields_for_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::FormBuilder#fields_for' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
allow(@new_post).to receive(:author).and_return(::Author.new)
end
context 'outside a form_for block' do
it 'yields an instance of FormHelper.builder' do
semantic_fields_for(@new_post) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
semantic_fields_for(@new_post.author) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
semantic_fields_for(:author, @new_post.author) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
semantic_fields_for(:author, @hash_backed_author) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
end
it 'should respond to input' do
semantic_fields_for(@new_post) do |nested_builder|
expect(nested_builder.respond_to?(:input)).to be_truthy
end
semantic_fields_for(@new_post.author) do |nested_builder|
expect(nested_builder.respond_to?(:input)).to be_truthy
end
semantic_fields_for(:author, @new_post.author) do |nested_builder|
expect(nested_builder.respond_to?(:input)).to be_truthy
end
semantic_fields_for(:author, @hash_backed_author) do |nested_builder|
expect(nested_builder.respond_to?(:input)).to be_truthy
end
end
end
context 'within a form_for block' do
it 'yields an instance of FormHelper.builder' do
semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(:author) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
end
end
it 'yields an instance of FormHelper.builder with hash-like model' do
semantic_form_for(:user) do |builder|
builder.semantic_fields_for(:author, @hash_backed_author) do |nested_builder|
expect(nested_builder.class).to eq(Formtastic::Helpers::FormHelper.builder)
end
end
end
it 'nests the object name' do
semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(@bob) do |nested_builder|
expect(nested_builder.object_name).to eq('post[author]')
end
end
end
it 'supports passing collection as second parameter' do
semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(:author, [@fred,@bob]) do |nested_builder|
expect(nested_builder.object_name).to match(/post\[author_attributes\]\[\d+\]/)
end
end
end
it 'should sanitize html id for li tag' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
concat(builder.semantic_fields_for(@bob, :index => 1) do |nested_builder|
concat(nested_builder.inputs(:login))
end)
end)
expect(output_buffer.to_str).to have_tag('form fieldset.inputs #post_author_1_login_input')
# Not valid selector, so using good ol' regex
expect(output_buffer.to_str).not_to match(/id="post\[author\]_1_login_input"/)
# <=> output_buffer.should_not have_tag('form fieldset.inputs #post[author]_1_login_input')
end
it 'should use namespace provided in nested fields' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob, :index => 1) do |nested_builder|
concat(nested_builder.inputs(:login))
end)
end)
expect(output_buffer.to_str).to have_tag('form fieldset.inputs #context2_post_author_1_login_input')
end
it 'should render errors on the nested inputs' do
@errors = double('errors')
allow(@errors).to receive(:[]).with(errors_matcher(:login)).and_return(['oh noes'])
allow(@bob).to receive(:errors).and_return(@errors)
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob) do |nested_builder|
concat(nested_builder.inputs(:login))
end)
end)
expect(output_buffer.to_str).to match(/oh noes/)
end
end
context "when I rendered my own hidden id input" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
expect(@fred.posts.size).to eq(1)
allow(@fred.posts.first).to receive(:persisted?).and_return(true)
allow(@fred).to receive(:posts_attributes=)
concat(semantic_form_for(@fred) do |builder|
concat(builder.semantic_fields_for(:posts) do |nested_builder|
concat(nested_builder.input(:id, :as => :hidden))
concat(nested_builder.input(:title))
end)
end)
end
it "should only render one hidden input (my one)" do
expect(output_buffer.to_str).to have_tag 'input#author_posts_attributes_0_id', :count => 1
end
it "should render the hidden input inside an li.hidden" do
expect(output_buffer.to_str).to have_tag 'li.hidden input#author_posts_attributes_0_id'
end
end
context "when FormBuilder.semantic_errors_link_to_inputs is true" do
before do
Formtastic::FormBuilder.semantic_errors_link_to_inputs = true
end
after do
Formtastic::FormBuilder.semantic_errors_link_to_inputs = false
end
context "when there are errors" do
before do
@errors = double('errors')
allow(@errors).to receive(:[]).with(errors_matcher(:login)).and_return(['oh noes'])
allow(@errors).to receive(:[]).with(errors_matcher(:name)).and_return([])
allow(@bob).to receive(:errors).and_return(@errors)
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob) do |nested_builder|
concat(nested_builder.inputs(:login, :name))
end)
end)
end
it 'should render errors on the nested inputs with default aria attributes' do
expect(output_buffer.to_str).to include('aria-invalid="true"')
expect(output_buffer.to_str).to \
have_tag 'input#context2_post_author_login[aria-describedby="login_error"]', \
count: 1
end
it 'should preserve developer-set aria attributes' do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob) do |nested_builder|
concat(nested_builder.input(:login, input_html: { 'aria-describedby': 'hint_for_email_field', 'aria-invalid': 'false' } ))
end)
end)
expect(output_buffer.to_str).to \
have_tag 'input#context2_post_author_login[aria-describedby="hint_for_email_field login_error"]', \
count: 1
expect(output_buffer.to_str).to \
have_tag 'input#context2_post_author_login[aria-invalid="false"]', \
count: 1
end
end
context "when there are no errors" do
before do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob) do |nested_builder|
concat(nested_builder.input(:login))
end)
end)
end
it 'should not aria attributes on nested inputs' do
expect(output_buffer.to_str).not_to include('aria-invalid')
expect(output_buffer.to_str).not_to include('aria-describedby')
end
it 'should render aria attributes I set' do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.semantic_fields_for(@bob) do |nested_builder|
concat(nested_builder.input(:login, input_html: { 'aria-describedby': 'hint_for_email_field', 'aria-invalid': 'false' } ))
end)
end)
expect(output_buffer.to_str).to include('aria-describedby="hint_for_email_field"')
expect(output_buffer.to_str).to include('aria-invalid="false"')
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/builder/error_proc_spec.rb | spec/builder/error_proc_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Rails field_error_proc' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it "should not be overridden globally for all form builders" do
current_field_error_proc = ::ActionView::Base.field_error_proc
semantic_form_for(@new_post) do |builder|
expect(::ActionView::Base.field_error_proc).not_to eq(current_field_error_proc)
end
expect(::ActionView::Base.field_error_proc).to eq(current_field_error_proc)
form_for(@new_post) do |builder|
expect(::ActionView::Base.field_error_proc).to eq(current_field_error_proc)
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/input_helper_spec.rb | spec/helpers/input_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'with input class finder' do
include_context 'form builder'
before do
@errors = double('errors')
allow(@errors).to receive(:[]).and_return([])
allow(@new_post).to receive(:errors).and_return(@errors)
end
describe 'arguments and options' do
it 'should require the first argument (the method on form\'s object)' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input()) # no args passed in at all
end)
}.to raise_error(ArgumentError)
end
describe ':required option' do
describe 'when true' do
it 'should set a "required" class' do
with_config :required_string, " required yo!" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => true))
end)
expect(output_buffer.to_str).not_to have_tag('form li.optional')
expect(output_buffer.to_str).to have_tag('form li.required')
end
end
it 'should append the "required" string to the label' do
with_config :required_string, " required yo!" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => true))
end)
expect(output_buffer.to_str).to have_tag('form li.required label', :text => /required yo/)
end
end
end
describe 'when false' do
before do
@string = Formtastic::FormBuilder.optional_string = " optional yo!" # ensure there's something in the string
expect(@new_post.class).not_to receive(:reflect_on_all_validations)
end
after do
Formtastic::FormBuilder.optional_string = ''
end
it 'should set an "optional" class' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => false))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should set and "optional" class also when there is presence validator' do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title])
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => false))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should append the "optional" string to the label' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => false))
end)
expect(output_buffer.to_str).to have_tag('form li.optional label', :text => /#{@string}$/)
end
end
describe 'when not provided' do
describe 'and an object was not given' do
it 'should use the default value' do
expect(Formtastic::FormBuilder.all_fields_required_by_default).to eq(true)
Formtastic::FormBuilder.all_fields_required_by_default = false
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
Formtastic::FormBuilder.all_fields_required_by_default = true
end
end
describe 'and an object with :validators_on was given (ActiveModel, Active Resource)' do
before do
allow(@new_post).to receive(:class).and_return(::PostModel)
end
after do
allow(@new_post).to receive(:class).and_return(::Post)
end
describe 'and validates_presence_of was called for the method' do
it 'should be required' do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title])
])
expect(@new_post.class).to receive(:validators_on).with(:body).at_least(:once).and_return([
active_model_presence_validator([:body], {:if => true})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
concat(builder.input(:body))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
it 'should be required when there is :on => :create option on create' do
with_config :required_string, " required yo!" do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => :create})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should be required when there is :create option in validation contexts array on create' do
with_config :required_string, " required yo!" do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => [:create]})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should be required when there is :on => :save option on create' do
with_config :required_string, " required yo!" do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => :save})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should be required when there is :save option in validation contexts array on create' do
with_config :required_string, " required yo!" do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => [:save]})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should be required when there is :on => :save option on update' do
with_config :required_string, " required yo!" do
expect(@fred.class).to receive(:validators_on).with(:login).at_least(:once).and_return([
active_model_presence_validator([:login], {:on => :save})
])
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:login))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should be required when there is :save option in validation contexts array on update' do
with_config :required_string, " required yo!" do
expect(@fred.class).to receive(:validators_on).with(:login).at_least(:once).and_return([
active_model_presence_validator([:login], {:on => [:save]})
])
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:login))
end)
expect(output_buffer.to_str).to have_tag('form li.required')
expect(output_buffer.to_str).not_to have_tag('form li.optional')
end
end
it 'should not be required when there is :on => :create option on update' do
expect(@fred.class).to receive(:validators_on).with(:login).at_least(:once).and_return([
active_model_presence_validator([:login], {:on => :create})
])
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:login))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should not be required when there is :create option in validation contexts array on update' do
expect(@fred.class).to receive(:validators_on).with(:login).at_least(:once).and_return([
active_model_presence_validator([:login], {:on => [:create]})
])
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:login))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should not be required when there is :on => :update option on create' do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => :update})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should not be required when there is :update option in validation contexts array on create' do
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(:once).and_return([
active_model_presence_validator([:title], {:on => [:update]})
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
it 'should be not be required if the optional :if condition is not satisifed' do
presence_should_be_required(:required => false, :tag => :body, :options => { :if => false })
end
it 'should not be required if the optional :if proc evaluates to false' do
presence_should_be_required(:required => false, :tag => :body, :options => { :if => proc { |record| false } })
end
it 'should be required if the optional :if proc evaluates to true' do
presence_should_be_required(:required => true, :tag => :body, :options => { :if => proc { |record| true } })
end
it 'should not be required if the optional :unless proc evaluates to true' do
presence_should_be_required(:required => false, :tag => :body, :options => { :unless => proc { |record| true } })
end
it 'should be required if the optional :unless proc evaluates to false' do
presence_should_be_required(:required => true, :tag => :body, :options => { :unless => proc { |record| false } })
end
it 'should be required if the optional :if with a method string evaluates to true' do
expect(@new_post).to receive(:required_condition).and_return(true)
presence_should_be_required(:required => true, :tag => :body, :options => { :if => :required_condition })
end
it 'should be required if the optional :if with a method string evaluates to false' do
expect(@new_post).to receive(:required_condition).and_return(false)
presence_should_be_required(:required => false, :tag => :body, :options => { :if => :required_condition })
end
it 'should be required if the optional :unless with a method string evaluates to false' do
expect(@new_post).to receive(:required_condition).and_return(false)
presence_should_be_required(:required => true, :tag => :body, :options => { :unless => :required_condition })
end
it 'should not be required if the optional :unless with a method string evaluates to true' do
expect(@new_post).to receive(:required_condition).and_return(true)
presence_should_be_required(:required => false, :tag => :body, :options => { :unless => :required_condition })
end
end
describe 'and validates_inclusion_of was called for the method' do
it 'should be required' do
expect(@new_post.class).to receive(:validators_on).with(:published).at_least(:once).and_return([
active_model_inclusion_validator([:published], {:in => [false, true]})
])
should_be_required(:tag => :published, :required => true)
end
it 'should not be required if allow_blank is true' do
expect(@new_post.class).to receive(:validators_on).with(:published).at_least(:once).and_return([
active_model_inclusion_validator([:published], {:in => [false, true], :allow_blank => true})
])
should_be_required(:tag => :published, :required => false)
end
end
describe 'and validates_length_of was called for the method' do
it 'should be required if minimum is set' do
length_should_be_required(:tag => :title, :required => true, :options => {:minimum => 1})
end
it 'should be required if :within is set' do
length_should_be_required(:tag => :title, :required => true, :options => {:within => 1..5})
end
it 'should not be required if :within allows zero length' do
length_should_be_required(:tag => :title, :required => false, :options => {:within => 0..5})
end
it 'should not be required if only :minimum is zero' do
length_should_be_required(:tag => :title, :required => false, :options => {:minimum => 0})
end
it 'should not be required if only :minimum is not set' do
length_should_be_required(:tag => :title, :required => false, :options => {:maximum => 5})
end
it 'should not be required if allow_blank is true' do
length_should_be_required(:tag => :published, :required => false, :options => {:allow_blank => true})
end
end
def add_presence_validator(options)
allow(@new_post.class).to receive(:validators_on).with(options[:tag]).and_return([
active_model_presence_validator([options[:tag]], options[:options])
])
end
def add_length_validator(options)
expect(@new_post.class).to receive(:validators_on).with(options[:tag]).at_least(:once) {[
active_model_length_validator([options[:tag]], options[:options])
]}
end
# TODO make a matcher for this?
def should_be_required(options)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(options[:tag]))
end)
if options[:required]
expect(output_buffer.to_str).not_to have_tag('form li.optional')
expect(output_buffer.to_str).to have_tag('form li.required')
else
expect(output_buffer.to_str).to have_tag('form li.optional')
expect(output_buffer.to_str).not_to have_tag('form li.required')
end
end
def presence_should_be_required(options)
add_presence_validator(options)
should_be_required(options)
end
def length_should_be_required(options)
add_length_validator(options)
should_be_required(options)
end
# TODO JF reversed this during refactor, need to make sure
describe 'and there are no requirement validations on the method' do
before do
expect(@new_post.class).to receive(:validators_on).with(:title).and_return([])
end
it 'should not be required' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
end
end
end
describe 'and an object without :validators_on' do
it 'should use the default value' do
expect(Formtastic::FormBuilder.all_fields_required_by_default).to eq(true)
Formtastic::FormBuilder.all_fields_required_by_default = false
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).not_to have_tag('form li.required')
expect(output_buffer.to_str).to have_tag('form li.optional')
Formtastic::FormBuilder.all_fields_required_by_default = true
end
end
end
end
describe ':as option' do
describe 'when not provided' do
it 'should default to a string for forms without objects unless column is password' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:anything))
end)
expect(output_buffer.to_str).to have_tag('form li.string')
end
it 'should default to password for forms without objects if column is password' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:password))
concat(builder.input(:password_confirmation))
concat(builder.input(:confirm_password))
end)
expect(output_buffer.to_str).to have_tag('form li.password', :count => 3)
end
it 'should default to a string for methods on objects that don\'t respond to "column_for_attribute"' do
allow(@new_post).to receive(:method_without_a_database_column)
allow(@new_post).to receive(:column_for_attribute).and_return(nil)
expect(default_input_type(nil, :method_without_a_database_column)).to eq(:string)
end
it 'should default to :password for methods that don\'t have a column in the database but "password" is in the method name' do
allow(@new_post).to receive(:password_method_without_a_database_column)
allow(@new_post).to receive(:column_for_attribute).and_return(nil)
expect(default_input_type(nil, :password_method_without_a_database_column)).to eq(:password)
end
it 'should default to :password for methods on objects that don\'t respond to "column_for_attribute" but "password" is in the method name' do
allow(@new_post).to receive(:password_method_without_a_database_column)
allow(@new_post).to receive(:column_for_attribute).and_return(nil)
expect(default_input_type(nil, :password_method_without_a_database_column)).to eq(:password)
end
it 'should default to :number for "integer" column with name ending in "_id"' do
allow(@new_post).to receive(:aws_instance_id)
allow(@new_post).to receive(:column_for_attribute).with(:aws_instance_id).and_return(double('column', :type => :integer))
expect(default_input_type(:integer, :aws_instance_id)).to eq(:number)
end
it 'should default to :select for associations' do
allow(@new_post.class).to receive(:reflect_on_association).with(:user_id).and_return(double('ActiveRecord::Reflection::AssociationReflection'))
allow(@new_post.class).to receive(:reflect_on_association).with(:section_id).and_return(double('ActiveRecord::Reflection::AssociationReflection'))
expect(default_input_type(:integer, :user_id)).to eq(:select)
expect(default_input_type(:integer, :section_id)).to eq(:select)
end
it 'should default to :select for enum' do
statuses = ActiveSupport::HashWithIndifferentAccess.new("active"=>0, "inactive"=>1)
allow(@new_post.class).to receive(:statuses) { statuses }
allow(@new_post).to receive(:defined_enums) { {"status" => statuses } }
expect(default_input_type(:integer, :status)).to eq(:select)
end
it 'should default to :password for :string column types with "password" in the method name' do
expect(default_input_type(:string, :password)).to eq(:password)
expect(default_input_type(:string, :hashed_password)).to eq(:password)
expect(default_input_type(:string, :password_hash)).to eq(:password)
end
it 'should default to :text for :text column types' do
expect(default_input_type(:text)).to eq(:text)
end
it 'should default to :date_select for :date column types' do
expect(default_input_type(:date)).to eq(:date_select)
end
it 'should default to :text for :hstore, :json and :jsonb column types' do
expect(default_input_type(:hstore)).to eq(:text)
expect(default_input_type(:json)).to eq(:text)
expect(default_input_type(:jsonb)).to eq(:text)
end
it 'should default to :datetime_select for :datetime and :timestamp column types' do
expect(default_input_type(:datetime)).to eq(:datetime_select)
expect(default_input_type(:timestamp)).to eq(:datetime_select)
end
it 'should default to :time_select for :time column types' do
expect(default_input_type(:time)).to eq(:time_select)
end
it 'should default to :boolean for :boolean column types' do
expect(default_input_type(:boolean)).to eq(:boolean)
end
it 'should default to :string for :string column types' do
expect(default_input_type(:string)).to eq(:string)
end
it 'should default to :string for :citext column types' do
expect(default_input_type(:citext)).to eq(:string)
end
it 'should default to :string for :inet column types' do
expect(default_input_type(:inet)).to eq(:string)
end
it 'should default to :number for :integer, :float and :decimal column types' do
expect(default_input_type(:integer)).to eq(:number)
expect(default_input_type(:float)).to eq(:number)
expect(default_input_type(:decimal)).to eq(:number)
end
it 'should default to :country for :string columns named country' do
expect(default_input_type(:string, :country)).to eq(:country)
end
it 'should default to :email for :string columns matching email' do
expect(default_input_type(:string, :email)).to eq(:email)
expect(default_input_type(:string, :customer_email)).to eq(:email)
expect(default_input_type(:string, :email_work)).to eq(:email)
end
it 'should default to :url for :string columns named url or website' do
expect(default_input_type(:string, :url)).to eq(:url)
expect(default_input_type(:string, :website)).to eq(:url)
expect(default_input_type(:string, :my_url)).to eq(:url)
expect(default_input_type(:string, :hurl)).not_to eq(:url)
end
it 'should default to :phone for :string columns named phone or fax' do
expect(default_input_type(:string, :phone)).to eq(:phone)
expect(default_input_type(:string, :fax)).to eq(:phone)
end
it 'should default to :search for :string columns named search' do
expect(default_input_type(:string, :search)).to eq(:search)
end
it 'should default to :color for :string columns matching color' do
expect(default_input_type(:string, :color)).to eq(:color)
expect(default_input_type(:string, :user_color)).to eq(:color)
expect(default_input_type(:string, :color_for_image)).to eq(:color)
end
describe 'defaulting to file column' do
Formtastic::FormBuilder.file_methods.each do |method|
it "should default to :file for attributes that respond to ##{method}" do
column = double('column')
Formtastic::FormBuilder.file_methods.each do |test|
### TODO: Check if this is ok
allow(column).to receive(method).with(test).and_return(method == test)
end
expect(@new_post).to receive(method).and_return(column)
semantic_form_for(@new_post) do |builder|
expect(builder.send(:default_input_type, method)).to eq(:file)
end
end
end
end
end
it 'should call the corresponding input class with .to_html' do
[:select, :time_zone, :radio, :date_select, :datetime_select, :time_select, :boolean, :check_boxes, :hidden, :string, :password, :number, :text, :file].each do |input_style|
allow(@new_post).to receive(:generic_column_name)
allow(@new_post).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
semantic_form_for(@new_post) do |builder|
input_instance = double('Input instance')
input_class = "#{input_style.to_s}_input".classify
input_constant = "Formtastic::Inputs::#{input_class}".constantize
expect(input_constant).to receive(:new).and_return(input_instance)
expect(input_instance).to receive(:to_html).and_return("some HTML")
concat(builder.input(:generic_column_name, :as => input_style))
end
end
end
end
describe ':label option' do
describe 'when provided' do
it 'should be passed down to the label tag' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => "Kustom"))
end)
expect(output_buffer.to_str).to have_tag("form li label", :text => /Kustom/)
end
it 'should not generate a label if false' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => false))
end)
expect(output_buffer.to_str).not_to have_tag("form li label")
end
it 'should be dupped if frozen' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => "Kustom".freeze))
end)
expect(output_buffer.to_str).to have_tag("form li label", :text => /Kustom/)
end
end
describe 'when not provided' do
describe 'when localized label is provided' do
describe 'and object is given' do
describe 'and label_str_method not :humanize' do
it 'should render a label with localized text and not apply the label_str_method' do
with_config :label_str_method, :reverse do
@localized_label_text = 'Localized title'
allow(@new_post).to receive(:meta_description)
::I18n.backend.store_translations :en,
:formtastic => {
:labels => {
:meta_description => @localized_label_text
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:meta_description))
end)
expect(output_buffer.to_str).to have_tag('form li label', :text => /Localized title/)
end
end
end
end
end
describe 'when localized label is NOT provided' do
describe 'and object is not given' do
it 'should default the humanized method name, passing it down to the label tag' do
::I18n.backend.store_translations :en, :formtastic => {}
with_config :label_str_method, :humanize do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:meta_description))
end)
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | true |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/actions_helper_spec.rb | spec/helpers/actions_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::FormBuilder#actions' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'with a block' do
describe 'when no options are provided' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.actions do
concat('hello')
end)
end)
end
it 'should render a fieldset inside the form, with a class of "actions"' do
expect(output_buffer.to_str).to have_tag("form fieldset.actions")
end
it 'should render an ol inside the fieldset' do
expect(output_buffer.to_str).to have_tag("form fieldset.actions ol")
end
it 'should render the contents of the block inside the ol' do
expect(output_buffer.to_str).to have_tag("form fieldset.actions ol", :text => /hello/)
end
it 'should not render a legend inside the fieldset' do
expect(output_buffer.to_str).not_to have_tag("form fieldset.actions legend")
end
end
describe 'when a :name option is provided' do
before do
@legend_text = "Advanced options"
concat(semantic_form_for(@new_post) do |builder|
builder.actions :name => @legend_text do
end
end)
end
it 'should render a fieldset inside the form' do
expect(output_buffer.to_str).to have_tag("form fieldset.actions legend", :text => /#{@legend_text}/)
end
end
describe 'when other options are provided' do
before do
@id_option = 'advanced'
@class_option = 'wide'
concat(semantic_form_for(@new_post) do |builder|
builder.actions :id => @id_option, :class => @class_option do
end
end)
end
it 'should pass the options into the fieldset tag as attributes' do
expect(output_buffer.to_str).to have_tag("form fieldset##{@id_option}")
expect(output_buffer.to_str).to have_tag("form fieldset.#{@class_option}")
end
end
end
describe 'without a block' do
describe 'with no args (default buttons)' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.actions)
end)
end
it 'should render a form' do
expect(output_buffer.to_str).to have_tag('form')
end
it 'should render an actions fieldset inside the form' do
expect(output_buffer.to_str).to have_tag('form fieldset.actions')
end
it 'should not render a legend in the fieldset' do
expect(output_buffer.to_str).not_to have_tag('form fieldset.actions legend')
end
it 'should render an ol in the fieldset' do
expect(output_buffer.to_str).to have_tag('form fieldset.actions ol')
end
it 'should render a list item in the ol for each default action' do
expect(output_buffer.to_str).to have_tag('form fieldset.actions ol li.action.input_action', :count => 1)
end
end
describe 'with button names as args' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.actions(:submit, :cancel, :reset))
end)
end
it 'should render a form with a fieldset containing a list item for each button arg' do
expect(output_buffer.to_str).to have_tag('form > fieldset.actions > ol > li.action', :count => 3)
end
end
describe 'with button names as args and an options hash' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.actions(:submit, :cancel, :reset, :name => "Now click a button", :id => "my-id"))
end)
end
it 'should render a form with a fieldset containing a list item for each button arg' do
expect(output_buffer.to_str).to have_tag('form > fieldset.actions > ol > li.action', :count => 3)
end
it 'should pass the options down to the fieldset' do
expect(output_buffer.to_str).to have_tag('form > fieldset#my-id.actions')
end
it 'should use the special :name option as a text for the legend tag' do
expect(output_buffer.to_str).to have_tag('form > fieldset#my-id.actions > legend', :text => /Now click a button/)
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/semantic_errors_helper_spec.rb | spec/helpers/semantic_errors_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::FormBuilder#semantic_errors' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
@title_errors = ['must not be blank', 'must be awesome']
@base_errors = ['base error message', 'nasty error']
@base_error = ['one base error']
@errors = double('errors')
allow(@new_post).to receive(:errors).and_return(@errors)
end
describe 'when there is only one error on base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors).to have_tag('ul.errors li', text: 'one base error')
end
end
end
describe 'when there is more than one error on base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_errors)
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors).to have_tag('ul.errors')
@base_errors.each do |error|
expect(builder.semantic_errors).to have_tag('ul.errors li', :text => error)
end
end
end
end
describe 'when there are errors on title' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return(@title_errors)
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return([])
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
title_name = builder.send(:localized_string, :title, :title, :label) || builder.send(:humanized_attribute_name, :title)
expect(builder.semantic_errors(:title)).to have_tag('ul.errors li', :text => title_name << " " << @title_errors.to_sentence)
end
end
end
describe 'when there are errors on title and base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return(@title_errors)
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
title_name = builder.send(:localized_string, :title, :title, :label) || builder.send(:humanized_attribute_name, :title)
expect(builder.semantic_errors(:title)).to have_tag('ul.errors li', :text => title_name << " " << @title_errors.to_sentence)
expect(builder.semantic_errors(:title)).to have_tag('ul.errors li', text: 'one base error')
end
end
end
describe 'when there are no errors' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return([])
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return([])
end
it 'should return nil' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(:title)).to be_nil
end
end
end
describe 'when there is one error on base and options with class is passed' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list with given class' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(:class => "awesome")).to have_tag('ul.awesome li', text: 'one base error')
end
end
end
describe 'when :base is passed in as an argument' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should ignore :base and only render base errors once' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(:base)).to have_tag('ul li', :count => 1)
expect(builder.semantic_errors(:base)).not_to have_tag('ul li', :text => "Base #{@base_error}")
end
end
end
context 'when configure FormBuilder.semantic_errors_link_to_inputs is true' do
before do
Formtastic::FormBuilder.semantic_errors_link_to_inputs = true
end
after do
Formtastic::FormBuilder.semantic_errors_link_to_inputs = false
end
describe 'when there is only one error on base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors).to have_tag('ul.errors li', text: 'one base error')
end
end
end
describe 'when there is more than one error on base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_errors)
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors).to have_tag('ul.errors')
@base_errors.each do |error|
expect(builder.semantic_errors).to have_tag('ul.errors li', :text => error)
end
end
end
end
describe 'when there are errors on title' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return(@title_errors)
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return([])
end
it 'should render an unordered list' do
semantic_form_for(@new_post) do |builder|
title_name = builder.send(:localized_string, :title, :title, :label) || builder.send(:humanized_attribute_name, :title)
expect(builder.semantic_errors(:title)).to have_tag('ul.errors li a', :text => title_name << " " << @title_errors.to_sentence)
end
end
end
describe 'when there are errors on title and base' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return(@title_errors)
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list where base has no link, and title error attribute links to title input field' do
semantic_form_for(@new_post) do |builder|
title_name = builder.send(:localized_string, :title, :title, :label) || builder.send(:humanized_attribute_name, :title)
expect(builder.semantic_errors(:title)).to \
have_tag('ul.errors li a',
with: { href: "##{@new_post.model_name}_title" },
text: title_name << " " << @title_errors.to_sentence
)
expect(builder.semantic_errors(:title)).to have_tag('ul.errors li', text: 'one base error')
end
end
end
describe 'when there are no errors' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:title)).and_return([])
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return([])
end
it 'should return nil' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(:title)).to be_nil
end
end
end
describe 'when there is one error on base and options with class is passed' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should render an unordered list with given class' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(class: "awesome")).to have_tag('ul.awesome li', text: 'one base error')
end
end
end
describe 'when :base is passed in as an argument' do
before do
allow(@errors).to receive(:[]).with(errors_matcher(:base)).and_return(@base_error)
end
it 'should ignore :base and only render base errors once' do
semantic_form_for(@new_post) do |builder|
expect(builder.semantic_errors(:base)).to have_tag('ul li', count: 1)
expect(builder.semantic_errors(:base)).not_to have_tag('ul li', text: "Base #{@base_error}")
end
end
end
end # context 'when semantic_errors_link_to_inputs is true'
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/reflection_helper_spec.rb | spec/helpers/reflection_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::Helpers::Reflection' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
class ReflectionTester
include Formtastic::Helpers::Reflection
def initialize(model_object)
@object = model_object
end
end
context 'with an ActiveRecord object' do
it "should return association details on an ActiveRecord association" do
@reflection_tester = ReflectionTester.new(@new_post)
expect(@reflection_tester.reflection_for(:sub_posts)).not_to be_nil
end
it "should return association details on a MongoMapper association" do
@reflection_tester = ReflectionTester.new(@new_mm_post)
expect(@reflection_tester.reflection_for(:sub_posts)).not_to be_nil
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/inputs_helper_spec.rb | spec/helpers/inputs_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::FormBuilder#inputs' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'with a block (block forms syntax)' do
describe 'when no options are provided' do
before do
@output_buffer = ActionView::OutputBuffer.new 'before_builder' # replace the output buffer and with one set to before_builder
concat(semantic_form_for(@new_post) do |builder|
@inputs_output = builder.inputs do
concat('hello')
end
end)
end
it 'should output just the content wrapped in inputs, not the whole template' do
expect(output_buffer.to_str).to match(/before_builder/)
expect(@inputs_output).not_to match(/before_builder/)
end
it 'should render a fieldset inside the form, with a class of "inputs"' do
expect(output_buffer.to_str).to have_tag("form fieldset.inputs")
end
it 'should render an ol inside the fieldset' do
expect(output_buffer.to_str).to have_tag("form fieldset.inputs ol")
end
it 'should render the contents of the block inside the ol' do
expect(output_buffer.to_str).to have_tag("form fieldset.inputs ol", :text => /hello/)
end
it 'should not render a legend inside the fieldset' do
expect(output_buffer.to_str).not_to have_tag("form fieldset.inputs legend")
end
it 'should render a fieldset even if no object is given' do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
@inputs_output = builder.inputs do
concat('bye')
end
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs ol", :text => /bye/)
end
end
describe 'when a :for option is provided' do
before do
allow(@new_post).to receive(:respond_to?).and_return(true, true)
allow(@new_post).to receive(:respond_to?).with(:empty?).and_return(false)
allow(@new_post).to receive(:author).and_return(@bob)
end
it 'should render nested inputs' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
inputs = builder.inputs :for => [:author, @bob] do |bob_builder|
concat(bob_builder.input(:login))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs #post_author_attributes_login")
expect(output_buffer.to_str).not_to have_tag("form fieldset.inputs #author_login")
end
it 'should concat rendered nested inputs to the template' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
builder.inputs :for => [:author, @bob] do |bob_builder|
concat(bob_builder.input(:login))
end
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs #post_author_attributes_login")
expect(output_buffer.to_str).not_to have_tag("form fieldset.inputs #author_login")
end
describe "as a symbol representing the association name" do
it 'should nest the inputs with an _attributes suffix on the association name' do
concat(semantic_form_for(@new_post) do |post|
inputs = post.inputs :for => :author do |author|
concat(author.input(:login))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag("form input[@name='post[author_attributes][login]']")
end
end
describe "as a symbol representing a has_many association name" do
before do
allow(@new_post).to receive(:authors).and_return([@bob, @fred])
allow(@new_post).to receive(:authors_attributes=)
end
it 'should nest the inputs with a fieldset, legend and :name input for each item' do
concat(semantic_form_for(@new_post) do |post|
post.inputs :for => :authors, :name => '%i' do |author|
concat(author.input(:login))
end
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs", :count => 2)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs legend", :count => 2)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs legend", :text => "1", :count => 1)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs legend", :text => "2")
expect(output_buffer.to_str).to have_tag("form input[@name='post[authors_attributes][0][login]']")
expect(output_buffer.to_str).to have_tag("form input[@name='post[authors_attributes][1][login]']")
expect(output_buffer.to_str).not_to have_tag('form fieldset[@name]')
end
it 'should include an indexed :label input for each item' do
concat(semantic_form_for(@new_post) do |post|
post.inputs :for => :authors do |author, index|
concat(author.input(:login, :label => "#{index}", :required => false))
end
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs label", :text => "1", :count => 1)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs label", :text => "2", :count => 1)
expect(output_buffer.to_str).not_to have_tag('form fieldset legend')
end
end
describe 'as an array containing the a symbole for the association name and the associated object' do
it 'should nest the inputs with an _attributes suffix on the association name' do
concat(semantic_form_for(@new_post) do |post|
inputs = post.inputs :for => [:author, @new_post.author] do |author|
concat(author.input(:login))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag("form input[@name='post[author_attributes][login]']")
end
end
describe 'as an associated object' do
it 'should not nest the inputs with an _attributes suffix' do
concat(semantic_form_for(@new_post) do |post|
inputs = post.inputs :for => @new_post.author do |author|
concat(author.input(:login))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag("form input[@name='post[author][login]']")
end
end
it 'should raise an error if :for and block with no argument is given' do
semantic_form_for(@new_post) do |builder|
expect {
builder.inputs(:for => [:author, @bob]) do
#
end
}.to raise_error(ArgumentError, 'You gave :for option with a block to inputs method, but the block does not accept any argument.')
end
end
it 'should pass options down to semantic_fields_for' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
inputs = builder.inputs :for => [:author, @bob], :for_options => { :index => 10 } do |bob_builder|
concat(bob_builder.input(:login))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag('form fieldset ol li #post_author_attributes_10_login')
end
it 'should not add builder as a fieldset attribute tag' do
concat(semantic_form_for(@new_post) do |builder|
inputs = builder.inputs :for => [:author, @bob], :for_options => { :index => 10 } do |bob_builder|
concat('input')
end
concat(inputs)
end)
expect(output_buffer.to_str).not_to have_tag('fieldset[@builder="Formtastic::Helpers::FormHelper"]')
end
it 'should send parent_builder as an option to allow child index interpolation for legends' do
concat(semantic_form_for(@new_post) do |builder|
builder.instance_variable_set('@nested_child_index', 0)
inputs = builder.inputs :for => [:author, @bob], :name => 'Author #%i' do |bob_builder|
concat('input')
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag('fieldset legend', :text => 'Author #1')
end
it 'should also provide child index interpolation for legends when nested child index is a hash' do
concat(semantic_form_for(@new_post) do |builder|
builder.instance_variable_set('@nested_child_index', :author => 10)
inputs = builder.inputs :for => [:author, @bob], :name => 'Author #%i' do |bob_builder|
concat('input')
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag('fieldset legend', :text => 'Author #11')
end
it 'should send parent_builder as an option to allow child index interpolation for labels' do
concat(semantic_form_for(@new_post) do |builder|
builder.instance_variable_set('@nested_child_index', 'post[author_attributes]' => 0)
inputs = builder.inputs :for => [:author, @bob] do |bob_builder, index|
concat(bob_builder.input(:name, :label => "Author ##{index}", :required => false))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag('fieldset label', :text => 'Author #1')
end
it 'should also provide child index interpolation for labels when nested child index is a hash' do
concat(semantic_form_for(@new_post) do |builder|
builder.instance_variable_set('@nested_child_index', 'post[author_attributes]' => 10)
inputs = builder.inputs :for => [:author, @bob] do |bob_builder, index|
concat(bob_builder.input(:name, :label => "Author ##{index}", :required => false))
end
concat(inputs)
end)
expect(output_buffer.to_str).to have_tag('fieldset label', :text => 'Author #11')
end
end
describe 'when a :name or :title option is provided' do
describe 'and is a string' do
before do
@legend_text = "Advanced options"
@legend_text_using_name = "Advanced options 2"
@legend_text_using_title = "Advanced options 3"
@nested_forms_legend_text = "This is a nested form title"
concat(semantic_form_for(@new_post) do |builder|
inputs = builder.inputs @legend_text do
end
concat(inputs)
inputs = builder.inputs :name => @legend_text_using_name do
end
concat(inputs)
inputs = builder.inputs :title => @legend_text_using_title do
end
concat(inputs)
inputs = builder.inputs @nested_forms_legend_text, :for => :authors do |nf|
end
concat(inputs)
end)
end
# TODO: looks like the block isn't being called for the last assertion here
it 'should render a fieldset with a legend inside the form' do
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@legend_text}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@legend_text_using_name}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@legend_text_using_title}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@nested_forms_legend_text}$/)
end
end
describe 'and is a symbol' do
before do
@localized_legend_text = "Localized advanced options"
@localized_legend_text_using_name = "Localized advanced options 2"
@localized_legend_text_using_title = "Localized advanced options 3"
@localized_nested_forms_legend_text = "This is a localized nested form title"
::I18n.backend.store_translations :en, :formtastic => {
:titles => {
:post => {
:advanced_options => @localized_legend_text,
:advanced_options_using_name => @localized_legend_text_using_name,
:advanced_options_using_title => @localized_legend_text_using_title,
:nested_forms_title => @localized_nested_forms_legend_text
}
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs(:advanced_options) do
end)
concat(builder.inputs(:name => :advanced_options_using_name) do
end)
concat(builder.inputs(:title => :advanced_options_using_title) do
end)
concat(builder.inputs(:nested_forms_title, :for => :authors) do |nf|
end)
end)
end
# TODO: looks like the block isn't being called for the last assertion here
it 'should render a fieldset with a localized legend inside the form' do
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@localized_legend_text}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@localized_legend_text_using_name}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@localized_legend_text_using_title}$/)
expect(output_buffer.to_str).to have_tag("form fieldset legend", :text => /^#{@localized_nested_forms_legend_text}$/)
end
end
end
describe 'when other options are provided' do
before do
@id_option = 'advanced'
@class_option = 'wide'
concat(semantic_form_for(@new_post) do |builder|
builder.inputs :id => @id_option, :class => @class_option do
end
end)
end
it 'should pass the options into the fieldset tag as attributes' do
expect(output_buffer.to_str).to have_tag("form fieldset##{@id_option}")
expect(output_buffer.to_str).to have_tag("form fieldset.#{@class_option}")
end
end
end
describe 'without a block' do
before do
allow(::Post).to receive(:reflections).and_return({:author => double('reflection', :options => {}, :macro => :belongs_to),
:comments => double('reflection', :options => {}, :macro => :has_many) })
allow(@new_post).to receive(:title)
allow(@new_post).to receive(:body)
allow(@new_post).to receive(:author_id)
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :string, :limit => 255))
allow(@new_post).to receive(:column_for_attribute).with(:body).and_return(double('column', :type => :text))
allow(@new_post).to receive(:column_for_attribute).with(:created_at).and_return(double('column', :type => :datetime))
allow(@new_post).to receive(:column_for_attribute).with(:author).and_return(nil)
end
describe 'with no args (quick forms syntax)' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs)
end)
end
it 'should render a form' do
expect(output_buffer.to_str).to have_tag('form')
end
it 'should render a fieldset inside the form' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs')
end
it 'should not render a legend in the fieldset' do
expect(output_buffer.to_str).not_to have_tag('form > fieldset.inputs > legend')
end
it 'should render an ol in the fieldset' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol')
end
it 'should render a list item in the ol for each column and reflection' do
# Remove the :has_many macro and :created_at column
count = ::Post.content_columns.size + ::Post.reflections.size - 2
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li', :count => count)
end
it 'should render a string list item for title' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.string')
end
it 'should render a text list item for body' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.text')
end
it 'should render a select list item for author_id' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.select', :count => 1)
end
it 'should not render timestamps inputs by default' do
expect(output_buffer.to_str).not_to have_tag('form > fieldset.inputs > ol > li.datetime')
end
context "with non-standard foregin keys" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
end
it 'should respect foreign key while rendering select' do
concat(semantic_form_for(LegacyPost.new, {:url => '/'}) do |builder|
concat(builder.inputs)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.select select#legacy_post_post_author', :count => 1)
expect(output_buffer.to_str).not_to have_tag('input#legacy_post_post_author')
end
end
context "with a polymorphic association" do
before do
allow(@new_post).to receive(:commentable)
allow(@new_post.class).to receive(:reflections).and_return({
:commentable => double('macro_reflection', :options => { :polymorphic => true }, :macro => :belongs_to)
})
allow(@new_post).to receive(:column_for_attribute).with(:commentable).and_return(
double('column', :type => :integer)
)
end
it 'should not render an input for the polymorphic association (the collection class cannot be guessed)' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs)
end)
expect(output_buffer.to_str).not_to have_tag('li#post_commentable_input')
end
end
end
describe 'with column names as args (short hand forms syntax)' do
describe 'and an object is given' do
it 'should render a form with a fieldset containing two list items' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs(:title, :body))
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li', :count => 2)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.string')
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.text')
end
end
describe 'and no object is given' do
it 'should render a form with a fieldset containing two list items' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.inputs(:title, :body))
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.string', :count => 2)
end
end
context "with a polymorphic association" do
it 'should raise an error for polymorphic associations (the collection class cannot be guessed)' do
allow(@new_post).to receive(:commentable)
allow(@new_post.class).to receive(:reflections).and_return({
:commentable => double('macro_reflection', :options => { :polymorphic => true }, :macro => :belongs_to)
})
allow(@new_post).to receive(:column_for_attribute).with(:commentable).and_return(
double('column', :type => :integer)
)
allow(@new_post.class).to receive(:reflect_on_association).with(:commentable).and_return(
double('reflection', :macro => :belongs_to, :options => { :polymorphic => true })
)
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs :commentable)
end)
}.to raise_error(Formtastic::PolymorphicInputWithoutCollectionError)
end
end
end
describe 'when a :for option is provided' do
describe 'and an object is given' do
it 'should render nested inputs' do
allow(@bob).to receive(:column_for_attribute).and_return(double('column', :type => :string, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs(:login, :for => @bob))
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs #post_author_login")
expect(output_buffer.to_str).not_to have_tag("form fieldset.inputs #author_login")
end
end
describe 'and no object is given' do
it 'should render nested inputs' do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.inputs(:login, :for => @bob))
end)
expect(output_buffer.to_str).to have_tag("form fieldset.inputs #project_author_login")
expect(output_buffer.to_str).not_to have_tag("form fieldset.inputs #project_login")
end
end
end
describe 'with column names and an options hash as args' do
before do
concat(semantic_form_for(@new_post) do |builder|
@legend_text_using_option = "Legendary Legend Text"
@legend_text_using_arg = "Legendary Legend Text 2"
concat(builder.inputs(:title, :body, :name => @legend_text_using_option, :id => "my-id"))
concat(builder.inputs(@legend_text_using_arg, :title, :body, :id => "my-id-2"))
end)
end
it 'should render a form with a fieldset containing two list items' do
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li', :count => 4)
end
it 'should pass the options down to the fieldset' do
expect(output_buffer.to_str).to have_tag('form > fieldset#my-id.inputs')
end
it 'should use the special :name option as a text for the legend tag' do
expect(output_buffer.to_str).to have_tag('form > fieldset#my-id.inputs > legend', :text => /^#{@legend_text_using_option}$/)
expect(output_buffer.to_str).to have_tag('form > fieldset#my-id-2.inputs > legend', :text => /^#{@legend_text_using_arg}$/)
end
end
describe 'when a :except option is provided' do
describe 'and an object is given' do
it 'should render a form with a fieldset containing only string item' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs :except => :body)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li', :count => 2)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.string')
expect(output_buffer.to_str).not_to have_tag('form > fieldset.inputs > ol > li.text')
end
it 'should render a form with a fieldset containing only text item' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs :except => :title)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li', :count => 2)
expect(output_buffer.to_str).not_to have_tag('form > fieldset.inputs > ol > li.string')
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.text')
end
end
describe 'and no object is given' do
it 'should render a form with a fieldset containing two list items' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.inputs(:title, :body))
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li.string', :count => 2)
end
end
end
end
describe 'nesting' do
context "when not nested" do
it "should not wrap the inputs in an li block" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
end)
end)
expect(output_buffer.to_str).not_to have_tag('form > li')
end
end
context "when nested (with block)" do
it "should wrap the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs do
end)
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol')
end
end
context "when nested (with block and :for)" do
it "should wrap the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs(:for => :author) do |author_builder|
end)
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol')
end
end
context "when nested (without block)" do
it "should wrap the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs(:title))
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol')
end
end
context "when nested (without block, with :for)" do
it "should wrap the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs(:name, :for => :author))
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol')
end
end
context "when double nested" do
it "should wrap the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs do
concat(builder.inputs do
end)
end)
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol > li > fieldset.inputs > ol')
end
end
context "when several are nested" do
it "should wrap each of the nested inputs in an li block to maintain HTML validity" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.inputs do
concat(builder.inputs do
end)
concat(builder.inputs do
end)
end)
end)
expect(output_buffer.to_str).to have_tag('form > fieldset.inputs > ol > li > fieldset.inputs > ol', :count => 2)
end
end
end
describe 'when using MongoMapper associations ' do
def generate_form
semantic_form_for(@new_mm_post) do |builder|
builder.inputs :title, :sub_posts
end
end
it "should throw PolymorphicInputWithoutCollectionError on sub_posts" do
expect(::MongoPost).to receive(:associations).at_least(3).times
expect { generate_form }.to raise_error(Formtastic::PolymorphicInputWithoutCollectionError)
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/action_helper_spec.rb | spec/helpers/action_helper_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'with action class finder' do
include_context 'form builder'
describe 'arguments and options' do
it 'should require the first argument (the action method)' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action()) # no args passed in at all
end)
}.to raise_error(ArgumentError)
end
describe ':as option' do
describe 'when not provided' do
it 'should default to a commit for commit' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.action(:submit))
end)
expect(output_buffer.to_str).to have_tag('form li.action.input_action', :count => 1)
end
it 'should default to a button for reset' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.action(:reset))
end)
expect(output_buffer.to_str).to have_tag('form li.action.input_action', :count => 1)
end
it 'should default to a link for cancel' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.action(:cancel))
end)
expect(output_buffer.to_str).to have_tag('form li.action.link_action', :count => 1)
end
end
it 'should call the corresponding action class with .to_html' do
[:input, :button, :link].each do |action_style|
semantic_form_for(:project, :url => "http://test.host") do |builder|
action_instance = double('Action instance')
action_class = "#{action_style.to_s}_action".classify
action_constant = "Formtastic::Actions::#{action_class}".constantize
expect(action_constant).to receive(:new).and_return(action_instance)
expect(action_instance).to receive(:to_html).and_return("some HTML")
concat(builder.action(:submit, :as => action_style))
end
end
end
end
#describe ':label option' do
#
# describe 'when provided' do
# it 'should be passed down to the label tag' do
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:title, :label => "Kustom"))
# end)
# output_buffer.should have_tag("form li label", /Kustom/)
# end
#
# it 'should not generate a label if false' do
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:title, :label => false))
# end)
# output_buffer.should_not have_tag("form li label")
# end
#
# it 'should be dupped if frozen' do
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:title, :label => "Kustom".freeze))
# end)
# output_buffer.should have_tag("form li label", /Kustom/)
# end
# end
#
# describe 'when not provided' do
# describe 'when localized label is provided' do
# describe 'and object is given' do
# describe 'and label_str_method not :humanize' do
# it 'should render a label with localized text and not apply the label_str_method' do
# with_config :label_str_method, :reverse do
# @localized_label_text = 'Localized title'
# @new_post.stub(:meta_description)
# ::I18n.backend.store_translations :en,
# :formtastic => {
# :labels => {
# :meta_description => @localized_label_text
# }
# }
#
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:meta_description))
# end)
# output_buffer.should have_tag('form li label', /Localized title/)
# end
# end
# end
# end
# end
#
# describe 'when localized label is NOT provided' do
# describe 'and object is not given' do
# it 'should default the humanized method name, passing it down to the label tag' do
# ::I18n.backend.store_translations :en, :formtastic => {}
# with_config :label_str_method, :humanize do
# concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
# concat(builder.input(:meta_description))
# end)
# output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/)
# end
# end
# end
#
# describe 'and object is given' do
# it 'should delegate the label logic to class human attribute name and pass it down to the label tag' do
# @new_post.stub(:meta_description) # a two word method name
# @new_post.class.should_receive(:human_attribute_name).with('meta_description').and_return('meta_description'.humanize)
#
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:meta_description))
# end)
# output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/)
# end
# end
#
# describe 'and object is given with label_str_method set to :capitalize' do
# it 'should capitalize method name, passing it down to the label tag' do
# with_config :label_str_method, :capitalize do
# @new_post.stub(:meta_description)
#
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:meta_description))
# end)
# output_buffer.should have_tag("form li label", /#{'meta_description'.capitalize}/)
# end
# end
# end
# end
#
# describe 'when localized label is provided' do
# before do
# @localized_label_text = 'Localized title'
# @default_localized_label_text = 'Default localized title'
# ::I18n.backend.store_translations :en,
# :formtastic => {
# :labels => {
# :title => @default_localized_label_text,
# :published => @default_localized_label_text,
# :post => {
# :title => @localized_label_text,
# :published => @default_localized_label_text
# }
# }
# }
# end
#
# it 'should render a label with localized label (I18n)' do
# with_config :i18n_lookups_by_default, false do
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:title, :label => true))
# concat(builder.input(:published, :as => :boolean, :label => true))
# end)
# output_buffer.should have_tag('form li label', Regexp.new('^' + @localized_label_text))
# end
# end
#
# it 'should render a hint paragraph containing an optional localized label (I18n) if first is not set' do
# with_config :i18n_lookups_by_default, false do
# ::I18n.backend.store_translations :en,
# :formtastic => {
# :labels => {
# :post => {
# :title => nil,
# :published => nil
# }
# }
# }
# concat(semantic_form_for(@new_post) do |builder|
# concat(builder.input(:title, :label => true))
# concat(builder.input(:published, :as => :boolean, :label => true))
# end)
# output_buffer.should have_tag('form li label', Regexp.new('^' + @default_localized_label_text))
# end
# end
# end
# end
#
#end
#
describe ':wrapper_html option' do
describe 'when provided' do
it 'should be passed down to the li tag' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :wrapper_html => {:id => :another_id}))
end)
expect(output_buffer.to_str).to have_tag("form li#another_id")
end
it 'should append given classes to li default classes' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :wrapper_html => {:class => :another_class}))
end)
expect(output_buffer.to_str).to have_tag("form li.action")
expect(output_buffer.to_str).to have_tag("form li.input_action")
expect(output_buffer.to_str).to have_tag("form li.another_class")
end
it 'should allow classes to be an array' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :wrapper_html => {:class => [ :my_class, :another_class ]}))
end)
expect(output_buffer.to_str).to have_tag("form li.action")
expect(output_buffer.to_str).to have_tag("form li.input_action")
expect(output_buffer.to_str).to have_tag("form li.my_class")
expect(output_buffer.to_str).to have_tag("form li.another_class")
end
end
describe 'when not provided' do
it 'should use default id and class' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit))
end)
expect(output_buffer.to_str).to have_tag("form li#post_submit_action")
expect(output_buffer.to_str).to have_tag("form li.action")
expect(output_buffer.to_str).to have_tag("form li.input_action")
end
end
end
end
describe 'instantiating an action class' do
context 'when a class does not exist' do
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.action(:submit, :as => :non_existant)
end)
}.to raise_error(Formtastic::UnknownActionError)
end
end
context 'when a customized top-level class does not exist' do
it 'should instantiate the Formtastic action' do
action = double('action', :to_html => 'some HTML')
expect(Formtastic::Actions::ButtonAction).to receive(:new).and_return(action)
concat(semantic_form_for(@new_post) do |builder|
builder.action(:commit, :as => :button)
end)
end
end
describe 'when a top-level (custom) action class exists' do
it "should instantiate the top-level action instead of the Formtastic one" do
class ::ButtonAction < Formtastic::Actions::ButtonAction
end
action = double('action', :to_html => 'some HTML')
expect(Formtastic::Actions::ButtonAction).not_to receive(:new)
expect(::ButtonAction).to receive(:new).and_return(action)
concat(semantic_form_for(@new_post) do |builder|
builder.action(:commit, :as => :button)
end)
end
end
describe 'support for :as on each action' do
it "should raise an error when the action does not support the :as" do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :link))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :input))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :button))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
end
it "should not raise an error when the action does not support the :as" do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :link))
end)
}.not_to raise_error
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :input))
end)
}.not_to raise_error
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :button))
end)
}.not_to raise_error
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:reset, :as => :input))
end)
}.not_to raise_error
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:reset, :as => :button))
end)
}.not_to raise_error
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/helpers/form_helper_spec.rb | spec/helpers/form_helper_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'FormHelper' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe '#semantic_form_for' do
it 'yields an instance of Formtastic::FormBuilder' do
semantic_form_for(@new_post, :url => '/hello') do |builder|
expect(builder.class).to eq(Formtastic::FormBuilder)
end
end
it 'adds a class of "formtastic" to the generated form' do
concat(semantic_form_for(@new_post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.formtastic")
end
it 'does not add "novalidate" attribute to the generated form when configured to do so' do
with_config :perform_browser_validations, true do
concat(semantic_form_for(@new_post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).not_to have_tag("form[@novalidate]")
end
end
it 'adds "novalidate" attribute to the generated form when configured to do so' do
with_config :perform_browser_validations, false do
concat(semantic_form_for(@new_post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form[@novalidate]")
end
end
it 'allows form HTML to override "novalidate" attribute when configured to validate' do
with_config :perform_browser_validations, false do
concat(semantic_form_for(@new_post, :url => '/hello', :html => { :novalidate => true }) do |builder|
end)
expect(output_buffer.to_str).to have_tag("form[@novalidate]")
end
end
it 'allows form HTML to override "novalidate" attribute when configured to not validate' do
with_config :perform_browser_validations, true do
concat(semantic_form_for(@new_post, :url => '/hello', :html => { :novalidate => false }) do |builder|
end)
expect(output_buffer.to_str).not_to have_tag("form[@novalidate]")
end
end
it 'adds a class of "xyz" to the generated form' do
Formtastic::Helpers::FormHelper.default_form_class = 'xyz'
concat(semantic_form_for(::Post.new, :as => :post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.xyz")
end
it 'omits the leading spaces from the classes in the generated form when the default class is nil' do
Formtastic::Helpers::FormHelper.default_form_class = nil
concat(semantic_form_for(::Post.new, :as => :post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form[class='post']")
end
it 'adds class matching the object name to the generated form when a symbol is provided' do
concat(semantic_form_for(@new_post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.post")
concat(semantic_form_for(:project, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.project")
end
it 'adds class matching the :as option when provided' do
concat(semantic_form_for(@new_post, :as => :message, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.message")
concat(semantic_form_for([:admins, @new_post], :as => :message, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.message")
end
it 'adds class matching the object\'s class to the generated form when an object is provided' do
concat(semantic_form_for(@new_post) do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.post")
end
it 'adds a namespaced class to the generated form' do
concat(semantic_form_for(::Namespaced::Post.new, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.namespaced_post")
end
it 'adds a customized class to the generated form' do
Formtastic::Helpers::FormHelper.default_form_model_class_proc = lambda { |model_class_name| "#{model_class_name}_form" }
concat(semantic_form_for(@new_post, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.post_form")
concat(semantic_form_for(:project, :url => '/hello') do |builder|
end)
expect(output_buffer.to_str).to have_tag("form.project_form")
end
describe 'allows :html options' do
before(:example) do
concat(semantic_form_for(@new_post, :url => '/hello', :html => { :id => "something-special", :class => "something-extra", :multipart => true }) do |builder|
end)
end
it 'to add a id of "something-special" to generated form' do
expect(output_buffer.to_str).to have_tag("form#something-special")
end
it 'to add a class of "something-extra" to generated form' do
expect(output_buffer.to_str).to have_tag("form.something-extra")
end
it 'to add enctype="multipart/form-data"' do
expect(output_buffer.to_str).to have_tag('form[@enctype="multipart/form-data"]')
end
end
it 'can be called with a resource-oriented style' do
semantic_form_for(@new_post) do |builder|
expect(builder.object.class).to eq(::Post)
expect(builder.object_name).to eq("post")
end
end
it 'can be called with a generic style and instance variable' do
semantic_form_for(@new_post, :as => :post, :url => new_post_path) do |builder|
expect(builder.object.class).to eq(::Post)
expect(builder.object_name.to_s).to eq("post") # TODO: is this forced .to_s a bad assumption somewhere?
end
end
it 'can be called with a generic style and inline object' do
semantic_form_for(@new_post, :url => new_post_path) do |builder|
expect(builder.object.class).to eq(::Post)
expect(builder.object_name.to_s).to eq("post") # TODO: is this forced .to_s a bad assumption somewhere?
end
end
describe 'ActionView::Base.field_error_proc' do
around do |ex|
error_proc = Formtastic::Helpers::FormHelper.formtastic_field_error_proc
ex.run
Formtastic::Helpers::FormHelper.formtastic_field_error_proc = error_proc
end
it 'is set to no-op wrapper by default' do
semantic_form_for(@new_post, :url => '/hello') do |builder|
expect(::ActionView::Base.field_error_proc.call("html", nil)).to eq("html")
end
end
it 'is set to the configured custom field_error_proc' do
field_error_proc = double()
Formtastic::Helpers::FormHelper.formtastic_field_error_proc = field_error_proc
semantic_form_for(@new_post, :url => '/hello') do |builder|
expect(::ActionView::Base.field_error_proc).to eq(field_error_proc)
end
end
it 'is restored to its original value after the form is rendered' do
expect do
Formtastic::Helpers::FormHelper.formtastic_field_error_proc = proc {""}
semantic_form_for(@new_post, :url => '/hello') { |builder| }
end.not_to change(::ActionView::Base, :field_error_proc)
end
end
describe "with :builder option" do
it "yields an instance of the given builder" do
class MyAwesomeCustomBuilder < Formtastic::FormBuilder
end
semantic_form_for(@new_post, :url => '/hello', :builder => MyAwesomeCustomBuilder) do |builder|
expect(builder.class).to eq(MyAwesomeCustomBuilder)
end
end
end
describe 'with :namespace option' do
it "should set the custom_namespace" do
semantic_form_for(@new_post, :namespace => 'context2') do |builder|
expect(builder.dom_id_namespace).to eq('context2')
end
end
end
describe 'without :namespace option' do
it 'defaults to class settings' do
expect(Formtastic::FormBuilder).to receive(:custom_namespace).and_return('context2')
semantic_form_for(@new_post) do |builder|
expect(builder.dom_id_namespace).to eq('context2')
end
end
end
end
describe '#semantic_fields_for' do
it 'yields an instance of Formtastic::FormBuilder' do
semantic_fields_for(@new_post) do |builder|
expect(builder.class).to be(Formtastic::FormBuilder)
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/actions/button_action_spec.rb | spec/actions/button_action_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'ButtonAction', 'when submitting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :button))
end)
end
it 'should render a submit type of button' do
expect(output_buffer.to_str).to have_tag('li.action.button_action button[@type="submit"]')
end
end
RSpec.describe 'ButtonAction', 'when resetting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:reset, :as => :button))
end)
end
it 'should render a reset type of button' do
expect(output_buffer.to_str).to have_tag('li.action.button_action button[@type="reset"]', :text => "Reset Post")
end
it 'should not render a value attribute' do
expect(output_buffer.to_str).not_to have_tag('li.action.button_action button[@value]')
end
end
RSpec.describe 'InputAction', 'when cancelling' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'should raise an error' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :button))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/actions/input_action_spec.rb | spec/actions/input_action_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'InputAction', 'when submitting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :input))
end)
end
it 'should render a submit type of input' do
expect(output_buffer.to_str).to have_tag('li.action.input_action input[@type="submit"]')
end
end
RSpec.describe 'InputAction', 'when resetting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:reset, :as => :input))
end)
end
it 'should render a reset type of input' do
expect(output_buffer.to_str).to have_tag('li.action.input_action input[@type="reset"]')
end
end
RSpec.describe 'InputAction', 'when cancelling' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'should raise an error' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :input))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/actions/generic_action_spec.rb | spec/actions/generic_action_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'InputAction::Base' do
# Most basic Action class to test Base
class ::GenericAction
include ::Formtastic::Actions::Base
def supported_methods
[:submit, :reset, :cancel]
end
def to_html
wrapper do
builder.submit(text, button_html)
end
end
end
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'wrapping HTML' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :foo => 'bah' }
))
end)
end
it 'should add the #foo id to the li' do
expect(output_buffer.to_str).to have_tag('li#post_submit_action')
end
it 'should add the .action and .generic_action classes to the li' do
expect(output_buffer.to_str).to have_tag('li.action.generic_action')
end
it 'should pass :wrapper_html HTML attributes to the wrapper' do
expect(output_buffer.to_str).to have_tag('li.action.generic_action[@foo="bah"]')
end
context "when a custom :id is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :id => 'foo_bah_bing' }
))
end)
end
it "should use the custom id" do
expect(output_buffer.to_str).to have_tag('li#foo_bah_bing')
end
end
context "when a custom class is provided as a string" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :class => 'foo_bah_bing' }
))
end)
end
it "should add the custom class strng to the existing classes" do
expect(output_buffer.to_str).to have_tag('li.action.generic_action.foo_bah_bing')
end
end
context "when a custom class is provided as an array" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :class => ['foo_bah_bing', 'zing_boo'] }
))
end)
end
it "should add the custom class strng to the existing classes" do
expect(output_buffer.to_str).to have_tag('li.action.generic_action.foo_bah_bing.zing_boo')
end
end
end
describe 'button HTML' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:button_html => { :foo => 'bah' }
))
end)
end
it 'should pass :button_html HTML attributes to the button' do
expect(output_buffer.to_str).to have_tag('li.action.generic_action input[@foo="bah"]')
end
it 'should respect a default_commit_button_accesskey configuration with nil' do
with_config :default_commit_button_accesskey, nil do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
end)
expect(output_buffer.to_str).not_to have_tag('li.action input[@accesskey]')
end
end
it 'should respect a default_commit_button_accesskey configuration with a String' do
with_config :default_commit_button_accesskey, 's' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.action input[@accesskey="s"]')
end
end
it 'should respect an accesskey through options over configration' do
with_config :default_commit_button_accesskey, 's' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :accesskey => 'o'))
end)
expect(output_buffer.to_str).not_to have_tag('li.action input[@accesskey="s"]')
expect(output_buffer.to_str).to have_tag('li.action input[@accesskey="o"]')
end
end
end
describe 'labelling' do
describe 'when used without object' do
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:submit => 'Submit %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}',
:actions => {
:message => {
:submit => 'Submit message',
:reset => 'Reset message',
:cancel => 'Cancel message'
}
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Submit Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset Post"]')
end
it 'should render an input with custom resource name localized label' do
concat(semantic_form_for(:post, :as => :message, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Submit message"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel message"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset message"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:submit => 'Custom Submit',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:submit => 'Custom Submit %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Submit Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Submit"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
end
end
end
end
end
describe 'when used on a new record' do
before do
allow(@new_post).to receive(:new_record?).and_return(true)
end
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:create => 'Create %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}'
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Create Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel Post"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:create => 'Custom Create',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:create => 'Custom Create %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Create Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Create"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
end
end
end
end
end
describe 'when used on an existing record' do
before do
allow(@new_post).to receive(:persisted?).and_return(true)
end
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:update => 'Save %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}',
:actions => {
:message => {
:submit => 'Submit message',
:reset => 'Reset message',
:cancel => 'Cancel message'
}
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Save Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset Post"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel Post"]')
end
it 'should render an input with custom resource name localized label' do
concat(semantic_form_for(:post, :as => :message, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Submit message"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Cancel message"]')
expect(output_buffer.to_str).to have_tag('li.generic_action input[@value="Reset message"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.reload!
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:update => 'Custom Save',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:update => 'Custom Save %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Save Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Save"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer.to_str).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
::I18n.backend.store_translations :en, :formtastic => {}
end
end
end
end
end
end
describe 'when the model is two words' do
before do
output_buffer = ActionView::OutputBuffer.new ''
class ::UserPost
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
def id
end
def persisted?
end
# Rails does crappy human_name
def self.human_name
"User post"
end
end
@new_user_post = ::UserPost.new
allow(@new_user_post).to receive(:new_record?).and_return(true)
concat(semantic_form_for(@new_user_post, :url => '') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
end
it "should render the string as the value of the button" do
expect(output_buffer.to_str).to have_tag('li input[@value="Create User post"]')
expect(output_buffer.to_str).to have_tag('li input[@value="Reset User post"]')
expect(output_buffer.to_str).to have_tag('li input[@value="Cancel User post"]')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/actions/link_action_spec.rb | spec/actions/link_action_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'LinkAction', 'when cancelling' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
context 'without a :url' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :link))
end)
end
it 'should render a submit type of input' do
expect(output_buffer.to_str).to have_tag('li.action.link_action a[@href="javascript:history.back()"]')
end
end
context 'with a :url as String' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :link, :url => "http://foo.bah/baz"))
end)
end
it 'should render a submit type of input' do
expect(output_buffer.to_str).to have_tag('li.action.link_action a[@href="http://foo.bah/baz"]')
end
end
context 'with a :url as Hash' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:cancel, :as => :link, :url => { :action => "foo" }))
end)
end
it 'should render a submit type of input' do
expect(output_buffer.to_str).to have_tag('li.action.link_action a[@href="/mock/path"]')
end
end
end
RSpec.describe 'LinkAction', 'when submitting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'should raise an error' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :link))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
end
end
RSpec.describe 'LinkAction', 'when submitting' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'should raise an error' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:reset, :as => :link))
end)
}.to raise_error(Formtastic::UnsupportedMethodForAction)
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/generators/formtastic/stylesheets/stylesheets_generator_spec.rb | spec/generators/formtastic/stylesheets/stylesheets_generator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# Generators are not automatically loaded by Rails
require 'generators/formtastic/stylesheets/stylesheets_generator'
RSpec.describe Formtastic::StylesheetsGenerator do
# Tell the generator where to put its output (what it thinks of as Rails.root)
destination File.expand_path("../../../../../tmp", __FILE__)
before { prepare_destination }
describe 'no arguments' do
before { run_generator }
describe 'app/assets/stylesheets/formtastic.css' do
subject { file('app/assets/stylesheets/formtastic.css') }
it { is_expected.to exist }
it { is_expected.to contain ".formtastic" }
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/generators/formtastic/input/input_generator_spec.rb | spec/generators/formtastic/input/input_generator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'generators/formtastic/input/input_generator'
RSpec.describe Formtastic::InputGenerator do
include FormtasticSpecHelper
destination File.expand_path("../../../../../tmp", __FILE__)
before do
prepare_destination
end
after do
FileUtils.rm_rf(File.expand_path("../../../../../tmp", __FILE__))
end
describe 'without file name' do
it 'should raise Thor::RequiredArgumentMissingError' do
expect { run_generator }.to raise_error(Thor::RequiredArgumentMissingError)
end
end
describe "input generator with underscore definition" do
before { run_generator %w(hat_size)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
it { is_expected.to contain "def to_html"}
it { is_expected.to contain "include Formtastic::Inputs::Base"}
it { is_expected.not_to contain "super"}
end
end
describe "input generator with camelcase definition" do
before { run_generator %w(HatSize)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with camelcase Input name sufixed" do
before { run_generator %w(HatSizeInput)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with underscore _input name sufixed" do
before { run_generator %w(hat_size_input)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with underscore input name sufixed" do
before { run_generator %w(hat_sizeinput)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "override an existing input using extend" do
before { run_generator %w(string --extend)}
describe 'app/inputs/string_input.rb' do
subject{ file('app/inputs/string_input.rb')}
it { is_expected.to exist }
it { is_expected.to contain "class StringInput < Formtastic::Inputs::StringInput" }
it { is_expected.to contain "def to_html" }
it { is_expected.not_to contain "include Formtastic::Inputs::Base" }
it { is_expected.to contain "super" }
it { is_expected.not_to contain "def input_html_options" }
end
end
describe "extend an existing input" do
before { run_generator %w(FlexibleText --extend string)}
describe 'app/inputs/flexible_text_input.rb' do
subject{ file('app/inputs/flexible_text_input.rb')}
it { is_expected.to contain "class FlexibleTextInput < Formtastic::Inputs::StringInput" }
it { is_expected.to contain "def input_html_options" }
it { is_expected.not_to contain "include Formtastic::Inputs::Base" }
it { is_expected.not_to contain "def to_html" }
end
end
describe "provide a slashed namespace" do
before { run_generator %w(stuff/foo)}
describe 'app/inputs/stuff/foo_input.rb' do
subject{ file('app/inputs/stuff/foo_input.rb')}
it {is_expected.to exist}
it { is_expected.to contain "class Stuff::FooInput" }
it { is_expected.to contain "include Formtastic::Inputs::Base" }
end
end
describe "provide a camelized namespace" do
before { run_generator %w(Stuff::Foo)}
describe 'app/inputs/stuff/foo_input.rb' do
subject{ file('app/inputs/stuff/foo_input.rb')}
it {is_expected.to exist}
it { is_expected.to contain "class Stuff::FooInput" }
it { is_expected.to contain "include Formtastic::Inputs::Base" }
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/generators/formtastic/form/form_generator_spec.rb | spec/generators/formtastic/form/form_generator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# Generators are not automatically loaded by Rails
require 'generators/formtastic/form/form_generator'
RSpec.describe Formtastic::FormGenerator do
include FormtasticSpecHelper
# Tell the generator where to put its output (what it thinks of as Rails.root)
destination File.expand_path("../../../../../tmp", __FILE__)
before do
@output_buffer = ActionView::OutputBuffer.new ''
prepare_destination
mock_everything
allow(::Post).to receive(:reflect_on_all_associations).with(:belongs_to).and_return([
double('reflection', :name => :author, :options => {}, :klass => ::Author, :macro => :belongs_to),
double('reflection', :name => :reviewer, :options => {:class_name => 'Author'}, :klass => ::Author, :macro => :belongs_to),
double('reflection', :name => :main_post, :options => {}, :klass => ::Post, :macro => :belongs_to),
double('reflection', :name => :attachment, :options => {:polymorphic => true}, :macro => :belongs_to),
])
end
after do
FileUtils.rm_rf(File.expand_path("../../../../../tmp", __FILE__))
end
describe 'without model' do
it 'should raise Thor::RequiredArgumentMissingError' do
expect { run_generator }.to raise_error(Thor::RequiredArgumentMissingError)
end
end
describe 'with existing model' do
it 'should not raise an exception' do
expect { run_generator %w(Post) }.not_to raise_error
end
end
describe 'with attributes' do
before { run_generator %w(Post title:string author:references) }
describe 'render only the specified attributes' do
subject { file('app/views/posts/_form.html.erb') }
it { is_expected.to exist }
it { is_expected.to contain "<%= f.input :title %>" }
it { is_expected.to contain "<%= f.input :author %>" }
it { is_expected.not_to contain "<%= f.input :main_post %>" }
end
end
describe 'without attributes' do
before { run_generator %w(Post) }
subject { file('app/views/posts/_form.html.erb') }
describe 'content_columns' do
it { is_expected.to contain "<%= f.input :title %>" }
it { is_expected.to contain "<%= f.input :body %>" }
it { is_expected.not_to contain "<%= f.input :created_at %>" }
it { is_expected.not_to contain "<%= f.input :updated_at %>" }
end
describe 'reflection_on_association' do
it { is_expected.to contain "<%= f.input :author %>" }
it { is_expected.to contain "<%= f.input :reviewer %>" }
it { is_expected.to contain "<%= f.input :main_post %>" }
it { is_expected.not_to contain "<%= f.input :attachment %>" }
end
end
describe 'with template engine option' do
describe 'erb' do
before { run_generator %w(Post --template-engine erb) }
describe 'app/views/posts/_form.html.erb' do
subject { file('app/views/posts/_form.html.erb') }
it { is_expected.to exist }
it { is_expected.to contain "<%= semantic_form_for @post do |f| %>" }
end
end
describe 'haml' do
describe 'app/views/posts/_form.html.haml' do
before { run_generator %w(Post --template-engine haml) }
subject { file('app/views/posts/_form.html.haml') }
it { is_expected.to exist }
it { is_expected.to contain "= semantic_form_for @post do |f|" }
end
context 'with copy option' do
describe 'app/views/posts/_form.html.haml' do
before { run_generator %w(Post --copy --template-engine haml) }
subject { file('app/views/posts/_form.html.haml') }
it { is_expected.not_to exist }
end
end
end
describe 'slim' do
before { run_generator %w(Post --template-engine slim) }
describe 'app/views/posts/_form.html.slim' do
subject { file('app/views/posts/_form.html.slim') }
it { is_expected.to exist }
it { is_expected.to contain "= semantic_form_for @post do |f|" }
end
end
end
describe 'with copy option' do
before { run_generator %w(Post --copy) }
describe 'app/views/posts/_form.html.erb' do
subject { file('app/views/posts/_form.html.erb') }
it { is_expected.not_to exist }
end
end
describe 'with controller option' do
before { run_generator %w(Post --controller admin/posts) }
describe 'app/views/admin/posts/_form.html.erb' do
subject { file('app/views/admin/posts/_form.html.erb') }
it { is_expected.to exist }
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/generators/formtastic/install/install_generator_spec.rb | spec/generators/formtastic/install/install_generator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# Generators are not automatically loaded by Rails
require 'generators/formtastic/install/install_generator'
RSpec.describe Formtastic::InstallGenerator do
# Tell the generator where to put its output (what it thinks of as Rails.root)
destination File.expand_path("../../../../../tmp", __FILE__)
before { prepare_destination }
describe 'no arguments' do
before { run_generator }
describe 'config/initializers/formtastic.rb' do
subject { file('config/initializers/formtastic.rb') }
it { is_expected.to exist }
it { is_expected.to contain "#" }
end
describe 'lib/templates/erb/scaffold/_form.html.erb' do
subject { file('lib/templates/erb/scaffold/_form.html.erb') }
it { is_expected.to exist }
it { is_expected.to contain "<%%= semantic_form_for @<%= singular_name %> do |f| %>" }
end
end
describe 'haml' do
before { run_generator %w(--template-engine haml) }
describe 'lib/templates/erb/scaffold/_form.html.haml' do
subject { file('lib/templates/haml/scaffold/_form.html.haml') }
it { is_expected.to exist }
it { is_expected.to contain "= semantic_form_for @<%= singular_name %> do |f|" }
end
end
describe 'slim' do
before { run_generator %w(--template-engine slim) }
describe 'lib/templates/erb/scaffold/_form.html.slim' do
subject { file('lib/templates/slim/scaffold/_form.html.slim') }
it { is_expected.to exist }
it { is_expected.to contain "= semantic_form_for @<%= singular_name %> do |f|" }
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/custom_input_spec.rb | spec/inputs/custom_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
# TODO extract out
module TestInputs
def input_args
@template = self
@object = ::Post.new
@object_name = 'post'
@method = :title
@options = {}
@proc = Proc.new {}
@builder = Formtastic::FormBuilder.new(@object_name, @object, @template, @options)
[@builder, @template, @object, @object_name, @method, @options]
end
class ::UnimplementedInput
include Formtastic::Inputs::Base
end
class ::ImplementedInput < UnimplementedInput
def to_html
"some HTML output"
end
end
end
RSpec.describe 'AnyCustomInput' do
include TestInputs
describe "#to_html" do
describe 'without an implementation' do
it "should raise a NotImplementedError exception" do
expect { ::UnimplementedInput.new(*input_args).to_html }.to raise_error(NotImplementedError)
end
end
describe 'with an implementation' do
it "should raise a NotImplementedError exception" do
expect { ::ImplementedInput.new(*input_args).to_html }.to_not raise_error
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/url_input_spec.rb | spec/inputs/url_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'url input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:url))
end)
end
it_should_have_input_wrapper_with_class(:url)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_url_input")
it_should_have_label_with_text(/Url/)
it_should_have_label_for("post_url")
it_should_have_input_with_id("post_url")
it_should_have_input_with_type(:url)
it_should_have_input_with_name("post[url]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:url))
end)
end
it_should_have_input_wrapper_with_id("context2_post_url_input")
it_should_have_label_and_input_with_id("context2_post_url")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :url))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :url, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/placeholder_spec.rb | spec/inputs/placeholder_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'string input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
after do
::I18n.backend.reload!
end
describe "placeholder text" do
[:email, :number, :password, :phone, :search, :string, :url, :text, :date_picker, :time_picker, :datetime_picker].each do |type|
describe "for #{type} inputs" do
describe "when found in i18n" do
it "should have a placeholder containing i18n text" do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :title => 'War and Peace' }}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="War and Peace"]')
end
end
end
describe "when not found in i18n" do
it "should not have placeholder" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).not_to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder]')
end
end
describe "when found in i18n and :input_html" do
it "should favor :input_html" do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :title => 'War and Peace' }}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :placeholder => "Foo" }))
end)
expect(output_buffer.to_str).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="Foo"]')
end
end
end
describe "when found in :input_html" do
it "should use the :input_html placeholder" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :placeholder => "Untitled" }))
end)
expect(output_buffer.to_str).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="Untitled"]')
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/hidden_input_spec.rb | spec/inputs/hidden_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'hidden input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
concat(builder.input(:published, :as => :hidden, :input_html => {:value => true}))
concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'}))
end)
end
it_should_have_input_wrapper_with_class("hidden")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_secret_input")
it_should_not_have_a_label
it "should generate a input field" do
expect(output_buffer.to_str).to have_tag("form li input#post_secret")
expect(output_buffer.to_str).to have_tag("form li input#post_secret[@type=\"hidden\"]")
expect(output_buffer.to_str).to have_tag("form li input#post_secret[@name=\"post[secret]\"]")
end
it "should get value from the object" do
expect(output_buffer.to_str).to have_tag("form li input#post_secret[@type=\"hidden\"][@value=\"1\"]")
end
it "should pass any explicitly specified value - using :input_html options" do
expect(output_buffer.to_str).to have_tag("form li input#post_published[@type=\"hidden\"][@value=\"true\"]")
end
it "should pass any option specified using :input_html" do
expect(output_buffer.to_str).to have_tag("form li input#new_post_reviewer[@type=\"hidden\"][@class=\"new_post_reviewer\"]")
end
it "should not render inline errors" do
@errors = double('errors')
allow(@errors).to receive(:[]).with(errors_matcher(:secret)).and_return(["foo", "bah"])
allow(@new_post).to receive(:errors).and_return(@errors)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
end)
expect(output_buffer.to_str).not_to have_tag("form li p.inline-errors")
expect(output_buffer.to_str).not_to have_tag("form li ul.errors")
end
it "should not render inline hints" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden, :hint => "all your base are belong to use"))
end)
expect(output_buffer.to_str).not_to have_tag("form li p.inline-hints")
expect(output_buffer.to_str).not_to have_tag("form li ul.hints")
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:secret, :as => :hidden))
concat(builder.input(:published, :as => :hidden, :input_html => {:value => true}))
concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'}))
end)
end
attributes_to_check = [:secret, :published, :reviewer]
attributes_to_check.each do |a|
it_should_have_input_wrapper_with_id("context2_post_#{a}_input")
end
(attributes_to_check - [:reviewer]).each do |a|
it_should_have_input_with_id("context2_post_#{a}")
end
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :hidden))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
context "when required" do
it "should not add the required attribute to the input's html options" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :hidden, :required => true))
end)
expect(output_buffer.to_str).not_to have_tag("input[@required]")
end
end
context "when :autofocus is provided in :input_html" do
it "should not add the autofocus attribute to the input's html options" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :hidden, :input_html => {:autofocus => true}))
end)
expect(output_buffer.to_str).not_to have_tag("input[@autofocus]")
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/string_input_spec.rb | spec/inputs/string_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'string input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :string))
concat(builder.input(:status, :as => :string))
end)
end
it_should_have_input_wrapper_with_class(:string)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_title_input")
it_should_have_label_with_text(/Title/)
it_should_have_label_for("post_title")
it_should_have_input_with_id("post_title")
it_should_have_input_with_type(:text)
it_should_have_input_with_name("post[title]")
it_should_have_maxlength_matching_string_column_limit
it_should_have_maxlength_matching_integer_column_limit
it_should_use_default_text_field_size_when_not_nil(:string)
it_should_not_use_default_text_field_size_when_nil(:string)
it_should_apply_custom_input_attributes_when_input_html_provided(:string)
it_should_apply_custom_for_to_label_when_input_html_id_provided(:string)
it_should_apply_error_logic_for_input_type(:string)
def input_field_for_method_should_have_maxlength(method, maxlength)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(method))
end)
expect(output_buffer.to_str).to have_tag("form li input[@maxlength='#{maxlength}']")
end
describe 'and its a ActiveModel' do
let(:default_maxlength) { 50 }
before do
allow(@new_post).to receive(:class).and_return(::PostModel)
end
after do
allow(@new_post).to receive(:class).and_return(::Post)
end
describe 'and validates_length_of was called for the method' do
def should_have_maxlength(maxlength, options)
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(1).and_return([
active_model_length_validator([:title], options[:options])
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
expect(output_buffer.to_str).to have_tag("form li input##{@new_post.class.name.underscore}_title[@maxlength='#{maxlength}']")
end
it 'should have maxlength if the optional :if or :unless options are not supplied' do
should_have_maxlength(42, :options => {:maximum => 42})
end
it 'should have default maxlength if the optional :if condition is not satisifed' do
should_have_maxlength(default_maxlength, :options => {:maximum => 42, :if => false})
end
it 'should have default_maxlength if the optional :if proc evaluates to false' do
should_have_maxlength(default_maxlength, :options => {:maximum => 42, :if => proc { |record| false }})
end
it 'should have maxlength if the optional :if proc evaluates to true' do
should_have_maxlength(42, :options => { :maximum => 42, :if => proc { |record| true } })
end
it 'should have default maxlength if the optional :if with a method name evaluates to false' do
expect(@new_post).to receive(:specify_maxlength).at_least(1).and_return(false)
should_have_maxlength(default_maxlength, :options => { :maximum => 42, :if => :specify_maxlength })
end
it 'should have maxlength if the optional :if with a method name evaluates to true' do
expect(@new_post).to receive(:specify_maxlength).at_least(1).and_return(true)
should_have_maxlength(42, :options => { :maximum => 42, :if => :specify_maxlength })
end
it 'should have default maxlength if the optional :unless proc evaluates to true' do
should_have_maxlength(default_maxlength, :options => { :maximum => 42, :unless => proc { |record| true } })
end
it 'should have maxlength if the optional :unless proc evaluates to false' do
should_have_maxlength(42, :options => { :maximum => 42, :unless => proc { |record| false } })
end
it 'should have default maxlength if the optional :unless with a method name evaluates to true' do
expect(@new_post).to receive(:specify_maxlength).at_least(1).and_return(true)
should_have_maxlength(default_maxlength, :options => { :maximum => 42, :unless => :specify_maxlength })
end
it 'should have maxlength if the optional :unless with a method name evaluates to false' do
expect(@new_post).to receive(:specify_maxlength).at_least(1).and_return(false)
should_have_maxlength(42, :options => { :maximum => 42, :unless => :specify_maxlength })
end
end
describe 'any conditional validation' do
describe 'proc that calls an instance method' do
it 'calls the method on the object' do
expect(@new_post).to receive(:something?)
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(1).and_return([
active_model_presence_validator([:title], { :unless => -> { something? } })
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
end
end
describe 'proc with arity that calls an instance method' do
it 'calls the method on the object' do
expect(@new_post).to receive(:something?)
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(1).and_return([
active_model_presence_validator([:title], { :unless => ->(user) { user.something? } })
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
end
end
describe 'symbol method name' do
it 'calls the method on the object if the method exists' do
expect(@new_post).to receive(:something?)
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(1).and_return([
active_model_presence_validator([:title], { :unless => :something? })
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
end
end
describe 'any other conditional' do
it 'does not raise an error' do
@conditional = double()
expect(@new_post.class).to receive(:validators_on).with(:title).at_least(1).and_return([
active_model_presence_validator([:title], { :unless => @conditional })
])
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end)
end
end
end
end
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:title, :as => :string))
end)
end
it_should_have_input_wrapper_with_id("context2_post_title_input")
it_should_have_label_and_input_with_id("context2_post_title")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :string))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when no object is provided" do
before do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => :string))
end)
end
it_should_have_label_with_text(/Title/)
it_should_have_label_for("project_title")
it_should_have_input_with_id("project_title")
it_should_have_input_with_type(:text)
it_should_have_input_with_name("project[title]")
end
describe "when size is nil" do
before do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => :string, :input_html => {:size => nil}))
end)
end
it "should have no size attribute" do
expect(output_buffer.to_str).not_to have_tag("input[@size]")
end
end
describe "when required" do
context "and configured to use HTML5 attribute" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :string, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
context "and configured to not use HTML5 attribute" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, false do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :string, :required => true))
end)
expect(output_buffer.to_str).not_to have_tag("input[@required]")
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/radio_input_spec.rb | spec/inputs/radio_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'radio input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'for belongs_to association' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio, :value_as_class => true, :required => true))
end)
end
it_should_have_input_wrapper_with_class("radio")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_author_input")
it_should_have_a_nested_fieldset
it_should_have_a_nested_fieldset_with_class('choices')
it_should_have_a_nested_ordered_list_with_class('choices-group')
it_should_apply_error_logic_for_input_type(:radio)
it_should_use_the_collection_when_provided(:radio, 'input')
it 'should generate a legend containing a label with text for the input' do
expect(output_buffer.to_str).to have_tag('form li fieldset legend.label label')
expect(output_buffer.to_str).to have_tag('form li fieldset legend.label label', :text => /Author/)
end
it 'should not link the label within the legend to any input' do
expect(output_buffer.to_str).not_to have_tag('form li fieldset legend label[@for]')
end
it 'should generate an ordered list with a list item for each choice' do
expect(output_buffer.to_str).to have_tag('form li fieldset ol')
expect(output_buffer.to_str).to have_tag('form li fieldset ol li.choice', :count => ::Author.all.size)
end
it 'should have one option with a "checked" attribute' do
expect(output_buffer.to_str).to have_tag('form li input[@checked]', :count => 1)
end
describe "each choice" do
it 'should not give the choice label the .label class' do
expect(output_buffer.to_str).not_to have_tag('li.choice label.label')
end
it 'should not add the required attribute to each input' do
expect(output_buffer.to_str).not_to have_tag('li.choice input[@required]')
end
it 'should contain a label for the radio input with a nested input and label text' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', /#{author.to_label}/)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_id_#{author.id}']")
end
end
it 'should use values as li.class when value_as_class is true' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li.author_#{author.id} label")
end
end
it "should have a radio input" do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#post_author_id_#{author.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@type='radio']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='#{author.id}']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='post[author_id]']")
end
end
it "should mark input as checked if it's the the existing choice" do
expect(@new_post.author_id).to eq(@bob.id)
expect(@new_post.author.id).to eq(@bob.id)
expect(@new_post.author).to eq(@bob)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio))
end)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@checked='checked']")
end
it "should mark the input as disabled if options attached for disabling" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio, :collection => [["Test", 'test'], ["Try", "try", {:disabled => true}]]))
end)
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li label input[@value='test'][@disabled='disabled']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='try'][@disabled='disabled']")
end
it "should not contain invalid HTML attributes" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio))
end)
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li input[@find_options]")
end
end
describe 'and no object is given' do
before(:example) do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :radio, :collection => ::Author.all))
end)
end
it 'should generate a fieldset with legend' do
expect(output_buffer.to_str).to have_tag('form li fieldset legend', :text => /Author/)
end
it 'should generate an li tag for each item in the collection' do
expect(output_buffer.to_str).to have_tag('form li fieldset ol li', :count => ::Author.all.size)
end
it 'should generate labels for each item' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /#{author.to_label}/)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']")
end
end
it 'should html escape the label string' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :radio, :collection => [["<b>Item 1</b>", 1], ["<b>Item 2</b>", 2]]))
end)
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', text: %r{<b>Item [12]</b>}, count: 2)
end
it 'should generate inputs for each item' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#project_author_id_#{author.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@type='radio']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='#{author.id}']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='project[author_id]']")
end
end
end
end
describe 'for a enum column' do
before do
allow(@new_post).to receive(:status) { 'inactive' }
statuses = ActiveSupport::HashWithIndifferentAccess.new("active"=>0, "inactive"=>1)
allow(@new_post.class).to receive(:statuses) { statuses }
allow(@new_post).to receive(:defined_enums) { { "status" => statuses } }
end
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:status, :as => :radio))
end)
end
it 'should have a radio input for each defined enum status' do
expect(output_buffer.to_str).to have_tag("form li input[@name='post[status]'][@type='radio']", :count => @new_post.class.statuses.count)
@new_post.class.statuses.each do |label, value|
expect(output_buffer.to_str).to have_tag("form li input[@value='#{label}']")
expect(output_buffer.to_str).to have_tag("form li label", :text => /#{label.humanize}/)
end
end
it 'should have one radio input with a "checked" attribute' do
expect(output_buffer.to_str).to have_tag("form li input[@name='post[status]'][@checked]", :count => 1)
end
end
describe "with i18n of the legend label" do
before do
::I18n.backend.store_translations :en, :formtastic => { :labels => { :post => { :authors => "Translated!" }}}
with_config :i18n_lookups_by_default, true do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :radio))
end)
end
end
after do
::I18n.backend.reload!
end
it "should do foo" do
expect(output_buffer.to_str).to have_tag("legend.label label", :text => /Translated/)
end
end
describe "when :label option is set" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :radio, :label => 'The authors'))
end)
end
it "should output the correct label title" do
expect(output_buffer.to_str).to have_tag("legend.label label", :text => /The authors/)
end
end
describe "when :label option is false" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :radio, :label => false))
end)
end
it "should not output the legend" do
expect(output_buffer.to_str).not_to have_tag("legend.label")
expect(output_buffer.to_str).not_to include(">")
end
it "should not cause escaped HTML" do
expect(output_buffer.to_str).not_to include(">")
end
end
describe "when :required option is true" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :radio, :required => true))
end)
end
it "should output the correct label title" do
expect(output_buffer.to_str).to have_tag("legend.label label abbr")
end
end
describe "when :namespace is given on form" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post, :namespace => "custom_prefix") do |builder|
concat(builder.input(:authors, :as => :radio, :label => ''))
end)
expect(output_buffer.to_str).to match(/for="custom_prefix_post_author_ids_(\d+)"/)
expect(output_buffer.to_str).to match(/id="custom_prefix_post_author_ids_(\d+)"/)
end
it_should_have_input_wrapper_with_id("custom_prefix_post_authors_input")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :radio))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name_true")
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name_false")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when collection contains integers" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(:project) do |builder|
concat(builder.input(:author_id, :as => :radio, :collection => [1, 2, 3]))
end)
end
it 'should output the correct labels' do
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /1/)
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /2/)
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /3/)
end
end
describe "when collection contains symbols" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(:project) do |builder|
concat(builder.input(:author_id, :as => :radio, :collection => Set.new([["A", :a], ["B", :b], ["C", :c]])))
end)
end
it 'should output the correct labels' do
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /A/)
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /B/)
expect(output_buffer.to_str).to have_tag("li.choice label", :text => /C/)
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/time_zone_input_spec.rb | spec/inputs/time_zone_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'time_zone input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:time_zone))
end)
end
it_should_have_input_wrapper_with_class("time_zone")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_time_zone_input")
it_should_apply_error_logic_for_input_type(:time_zone)
it 'should generate a label for the input' do
expect(output_buffer.to_str).to have_tag('form li label')
expect(output_buffer.to_str).to have_tag('form li label[@for="post_time_zone"]')
expect(output_buffer.to_str).to have_tag('form li label', :text => /Time zone/)
end
it "should generate a select" do
expect(output_buffer.to_str).to have_tag("form li select")
expect(output_buffer.to_str).to have_tag("form li select#post_time_zone")
expect(output_buffer.to_str).to have_tag("form li select[@name=\"post[time_zone]\"]")
end
it 'should use input_html to style inputs' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:time_zone, :input_html => { :class => 'myclass' }))
end)
expect(output_buffer.to_str).to have_tag("form li select.myclass")
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:time_zone))
end)
end
it_should_have_input_wrapper_with_id("context2_post_time_zone_input")
it_should_have_select_with_id("context2_post_time_zone")
it_should_have_label_for("context2_post_time_zone")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :time_zone))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][name]']")
end
end
describe 'when no object is given' do
before(:example) do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:time_zone, :as => :time_zone))
end)
end
it 'should generate labels' do
expect(output_buffer.to_str).to have_tag('form li label')
expect(output_buffer.to_str).to have_tag('form li label[@for="project_time_zone"]')
expect(output_buffer.to_str).to have_tag('form li label', :text => /Time zone/)
end
it 'should generate select inputs' do
expect(output_buffer.to_str).to have_tag("form li select")
expect(output_buffer.to_str).to have_tag("form li select#project_time_zone")
expect(output_buffer.to_str).to have_tag("form li select[@name=\"project[time_zone]\"]")
end
end
context "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :time_zone, :required => true))
end)
expect(output_buffer.to_str).to have_tag("select[@required]")
end
end
end
describe "when priority time zone is provided" do
let(:time_zones) { [ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii']] }
let(:input_html_options) do
{ id: "post_title", required: false, autofocus: false, readonly: false }
end
context "by priority_zone option" do
it "passes right time_zones" do
expect_any_instance_of(Formtastic::FormBuilder).to receive(:time_zone_select).with(:title, time_zones, {}, input_html_options)
semantic_form_for(@new_post) do |builder|
builder.input(:title, as: :time_zone, priority_zones: time_zones)
end
end
end
context "by configuration" do
it "passes right time_zones" do
expect_any_instance_of(Formtastic::FormBuilder).to receive(:time_zone_select).with(:title, time_zones, {}, input_html_options)
with_config :priority_time_zones, time_zones do
semantic_form_for(@new_post) do |builder|
builder.input(:title, as: :time_zone)
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/password_input_spec.rb | spec/inputs/password_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'password input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :password))
end)
end
it_should_have_input_wrapper_with_class(:password)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_title_input")
it_should_have_label_with_text(/Title/)
it_should_have_label_for("post_title")
it_should_have_input_with_id("post_title")
it_should_have_input_with_type(:password)
it_should_have_input_with_name("post[title]")
it_should_have_maxlength_matching_string_column_limit
it_should_use_default_text_field_size_when_not_nil(:string)
it_should_not_use_default_text_field_size_when_nil(:string)
it_should_apply_custom_input_attributes_when_input_html_provided(:string)
it_should_apply_custom_for_to_label_when_input_html_id_provided(:string)
it_should_apply_error_logic_for_input_type(:password)
describe "when no object is provided" do
before do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => :password))
end)
end
it_should_have_label_with_text(/Title/)
it_should_have_label_for("project_title")
it_should_have_input_with_id("project_title")
it_should_have_input_with_type(:password)
it_should_have_input_with_name("project[title]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:title, :as => :password))
end)
end
it_should_have_input_wrapper_with_id("context2_post_title_input")
it_should_have_label_and_input_with_id("context2_post_title")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :password))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :password, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/readonly_spec.rb | spec/inputs/readonly_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'readonly option' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "placeholder text" do
[:email, :number, :password, :phone, :search, :string, :url, :text, :date_picker, :time_picker, :datetime_picker].each do |type|
describe "for #{type} inputs" do
describe "when readonly is found in input_html" do
it "sets readonly attribute" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, input_html: {readonly: true}))
end)
expect(output_buffer.to_str).to have_tag((type == :text ? 'textarea' : 'input') + '[@readonly]')
end
end
describe "when readonly not found in input_html" do
describe "when column is not readonly attribute" do
it "doesn't set readonly attribute" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).not_to have_tag((type == :text ? 'textarea' : 'input') + '[@readonly]')
end
end
describe "when column is readonly attribute" do
it "sets readonly attribute" do
input_class = "Formtastic::Inputs::#{type.to_s.camelize}Input".constantize
expect_any_instance_of(input_class).to receive(:readonly_attribute?).at_least(1).and_return(true)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end)
expect(output_buffer.to_str).to have_tag((type == :text ? 'textarea' : 'input') + '[@readonly]')
end
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/text_input_spec.rb | spec/inputs/text_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'text input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:body, :as => :text))
end)
end
it_should_have_input_wrapper_with_class("text")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_body_input")
it_should_have_label_with_text(/Body/)
it_should_have_label_for("post_body")
it_should_have_textarea_with_id("post_body")
it_should_have_textarea_with_name("post[body]")
it_should_apply_error_logic_for_input_type(:number)
it 'should use input_html to style inputs' do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :input_html => { :class => 'myclass' }))
end)
expect(output_buffer.to_str).to have_tag("form li textarea.myclass")
end
it "should have a cols attribute when :cols is a number in :input_html" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :input_html => { :cols => 42 }))
end)
expect(output_buffer.to_str).to have_tag("form li textarea[@cols='42']")
end
it "should not have a cols attribute when :cols is nil in :input_html" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :input_html => { :cols => nil }))
end)
expect(output_buffer.to_str).not_to have_tag("form li textarea[@cols]")
end
it "should have a rows attribute when :rows is a number in :input_html" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :input_html => { :rows => 42 }))
end)
expect(output_buffer.to_str).to have_tag("form li textarea[@rows='42']")
end
it "should not have a rows attribute when :rows is nil in :input_html" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :input_html => { :rows => nil }))
end)
expect(output_buffer.to_str).not_to have_tag("form li textarea[@rows]")
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:body, :as => :text))
end)
end
it_should_have_input_wrapper_with_id("context2_post_body_input")
it_should_have_textarea_with_id("context2_post_body")
it_should_have_label_for("context2_post_body")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :text))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("textarea#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("textarea[@name='post[author_attributes][3][name]']")
end
end
context "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text, :required => true))
end)
expect(output_buffer.to_str).to have_tag("textarea[@required]")
end
end
end
context "when :autofocus is provided in :input_html" do
before(:example) do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :input_html => {:autofocus => true}))
end)
end
it_should_have_input_wrapper_with_class("autofocus")
it "should add the autofocus attribute to the input's html options" do
expect(output_buffer.to_str).to have_tag("input[@autofocus]")
end
end
context "when :rows is missing in :input_html" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
end
it "should have a rows attribute matching default_text_area_height if numeric" do
with_config :default_text_area_height, 12 do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text))
end)
expect(output_buffer.to_str).to have_tag("form li textarea[@rows='12']")
end
end
it "should not have a rows attribute if default_text_area_height is nil" do
with_config :default_text_area_height, nil do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text))
end)
expect(output_buffer.to_str).not_to have_tag("form li textarea[@rows]")
end
end
end
context "when :cols is missing in :input_html" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
end
it "should have a cols attribute matching default_text_area_width if numeric" do
with_config :default_text_area_width, 10 do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text))
end)
expect(output_buffer.to_str).to have_tag("form li textarea[@cols='10']")
end
end
it "should not have a cols attribute if default_text_area_width is nil" do
with_config :default_text_area_width, nil do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :text))
end)
expect(output_buffer.to_str).not_to have_tag("form li textarea[@cols]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/number_input_spec.rb | spec/inputs/number_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'number input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than=>2})
])
end
describe "all cases" do
before do
concat(
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :number))
end
)
end
it_should_have_input_wrapper_with_class(:number)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:numeric)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_title_input")
it_should_have_label_with_text(/Title/)
it_should_have_label_for("post_title")
it_should_have_input_with_id("post_title")
it_should_have_input_with_type(:number)
it_should_have_input_with_name("post[title]")
# @todo this is not testing what it should be testing!
# it_should_use_default_text_field_size_when_not_nil(:string)
# it_should_not_use_default_text_field_size_when_nil(:string)
# it_should_apply_custom_input_attributes_when_input_html_provided(:string)
# it_should_apply_custom_for_to_label_when_input_html_id_provided(:string)
it_should_apply_error_logic_for_input_type(:number)
end
describe "when no object is provided" do
before do
concat(semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => :number, :input_html => { :min => 1, :max => 2 }))
end)
end
it_should_have_label_with_text(/Title/)
it_should_have_label_for("project_title")
it_should_have_input_with_id("project_title")
it_should_have_input_with_type(:number)
it_should_have_input_with_name("project[title]")
end
describe "when namespace provided" do
before do
concat(semantic_form_for(@new_post, :namespace => :context2) do |builder|
concat(builder.input(:title, :as => :number))
end)
end
it_should_have_input_wrapper_with_id("context2_post_title_input")
it_should_have_label_and_input_with_id("context2_post_title")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :number))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :number, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
describe "when validations require a minimum value (:greater_than)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than=>2})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a min attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="3"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
end
describe "when validations require a minimum value (:greater_than) that takes a proc" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than=> Proc.new {|post| 2}})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a min attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="3"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
end
describe "when validations require a minimum value (:greater_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than_or_equal_to=>2})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "when validations require a minimum value (:greater_than_or_equal_to) that takes a Proc" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than_or_equal_to=> Proc.new { |post| 2}})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "when validations require a maximum value (:less_than)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than=>20})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a max attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="19"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
describe "and the validator takes a proc" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
end
end
describe "when validations require a maximum value (:less_than) that takes a Proc" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than=> Proc.new {|post| 20 }})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a max attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="19"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
describe "and the validator takes a proc" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
end
end
describe "when validations require a maximum value (:less_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than_or_equal_to=>20})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "when validations require a maximum value (:less_than_or_equal_to) that takes a proc" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than_or_equal_to=> Proc.new { |post| 20 }})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "when validations require conflicting minimum values (:greater_than, :greater_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than => 20, :greater_than_or_equal_to=>2})
])
end
it "should add a max attribute to the input equal to the :greater_than_or_equal_to validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
describe "when validations require conflicting maximum values (:less_than, :less_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than => 20, :less_than_or_equal_to=>2})
])
end
it "should add a max attribute to the input equal to the :greater_than_or_equal_to validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@max="2"]')
end
end
describe "when validations require only an integer (:only_integer)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false, :only_integer=>true})
])
end
it "should add a step=1 attribute to the input to signify that only whole numbers are allowed" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@step="1"]')
end
it "should let input_html override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
describe "when validations require a :step (non standard)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false, :only_integer=>true, :step=>2})
])
end
it "should add a step=1 attribute to the input to signify that only whole numbers are allowed" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@step="2"]')
end
it "should let input_html override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
describe "when validations do not specify :step (non standard) or :only_integer" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false})
])
end
it "should default step to 'any'" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number)
end)
expect(output_buffer.to_str).to have_tag('input[@step="any"]')
end
it "should let input_html set :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options set :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :number, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/email_input_spec.rb | spec/inputs/email_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'email input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:email))
end)
end
it_should_have_input_wrapper_with_class(:email)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_email_input")
it_should_have_label_with_text(/Email/)
it_should_have_label_for("post_email")
it_should_have_input_with_id("post_email")
it_should_have_input_with_type(:email)
it_should_have_input_with_name("post[email]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:email))
end)
end
it_should_have_input_wrapper_with_id("context2_post_email_input")
it_should_have_label_and_input_with_id("context2_post_email")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :email))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :email, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/date_picker_input_spec.rb | spec/inputs/date_picker_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'date_picker input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
context "with an object" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_picker))
end)
end
it_should_have_input_wrapper_with_class(:date_picker)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_label_with_text(/Publish at/)
it_should_have_label_for("post_publish_at")
it_should_have_input_with_id("post_publish_at")
it_should_have_input_with_type(:date)
it_should_have_input_with_name("post[publish_at]")
it_should_apply_custom_input_attributes_when_input_html_provided(:date_picker)
it_should_apply_custom_for_to_label_when_input_html_id_provided(:date_picker)
# TODO why does this blow-up it_should_apply_error_logic_for_input_type(:date_picker)
end
describe "size attribute" do
it "defaults to 10 chars (YYYY-YY-YY)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[size='10']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :size => '12', :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='12']"
end
end
describe "maxlength attribute" do
it "defaults to 10 chars (YYYY-YY-YY)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='10']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :maxlength => 12, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='12']"
end
end
describe "value attribute" do
context "when method returns nil" do
it "has no value" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker ))
end
)
expect(output_buffer.to_str).not_to have_tag "li input[value]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :value => "1111-11-11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11']"
end
end
context "when method returns a Date" do
before do
@date = Date.new(2000, 11, 11)
allow(@new_post).to receive(:publish_at).and_return(@date)
end
it "renders the date as YYYY-MM-DD" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='#{@date.to_s}']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :value => "1111-11-11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11']"
end
end
context "when method returns a Time" do
before do
@time = Time.utc(2000,11,11,11,11,11)
allow(@new_post).to receive(:publish_at).and_return(@time)
end
it "renders the time as a YYYY-MM-DD" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='2000-11-11']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :value => "1111-11-11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11']"
end
end
context "when method returns an empty String" do
before do
allow(@new_post).to receive(:publish_at).and_return("")
end
it "will be empty" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :value => "1111-11-11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11']"
end
end
context "when method returns a String" do
before do
allow(@new_post).to receive(:publish_at).and_return("yeah")
end
it "will be the string" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='yeah']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :value => "1111-11-11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11']"
end
end
end
describe "min attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[min]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :min => "1970-01-01" }))
end
)
expect(output_buffer.to_str).to have_tag "input[min='1970-01-01']"
end
end
describe "max attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[max]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :max => "1970-01-01" }))
end
)
expect(output_buffer.to_str).to have_tag "input[max='1970-01-01']"
end
end
describe "step attribute" do
it "defaults to 1" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[step='1']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :step => "5" }))
end
)
expect(output_buffer.to_str).to have_tag "input[step='5']"
end
describe "macros" do
before do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :step => step }))
end
)
end
context ":day" do
let(:step) { :day }
it "uses 1" do
expect(output_buffer.to_str).to have_tag "input[step='1']"
end
end
context ":seven_days" do
let(:step) { :seven_days }
it "uses 7" do
expect(output_buffer.to_str).to have_tag "input[step='7']"
end
end
context ":week" do
let(:step) { :week }
it "uses 7" do
expect(output_buffer.to_str).to have_tag "input[step='7']"
end
end
context ":fortnight" do
let(:step) { :fortnight }
it "uses 14" do
expect(output_buffer.to_str).to have_tag "input[step='14']"
end
end
context ":two_weeks" do
let(:step) { :two_weeks }
it "uses 14" do
expect(output_buffer.to_str).to have_tag "input[step='14']"
end
end
context ":four_weeks" do
let(:step) { :four_weeks }
it "uses 28" do
expect(output_buffer.to_str).to have_tag "input[step='28']"
end
end
context ":thirty_days" do
let(:step) { :thirty_days }
it "uses 30" do
expect(output_buffer.to_str).to have_tag "input[step='30']"
end
end
end
end
describe "placeholder attribute" do
it "will be omitted" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[placeholder]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :placeholder => "1970-01-01" }))
end
)
expect(output_buffer.to_str).to have_tag "input[placeholder='1970-01-01']"
end
context "with i18n set" do
before do
::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :publish_at => 'YYYY-MM-DD' }}
end
it "can be set with i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_picker))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="YYYY-MM-DD"]')
end
end
it "can be set with input_html, trumping i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_picker, :input_html => { :placeholder => "Something" }))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="Something"]')
end
end
end
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:publish_at, :as => :date_picker))
end)
end
it_should_have_input_wrapper_with_id("context2_post_publish_at_input")
it_should_have_label_and_input_with_id("context2_post_publish_at")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :date_picker))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_picker, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/country_input_spec.rb | spec/inputs/country_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'country input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when country_select is not available as a helper from a plugin" do
it "should raise an error, suggesting the author installs a plugin" do
expect {
semantic_form_for(@new_post) do |builder|
concat(builder.input(:country, :as => :country))
end
}.to raise_error(Formtastic::Inputs::CountryInput::CountrySelectPluginMissing)
end
end
describe "when country_select is available as a helper (from a plugin)" do
before do
concat(semantic_form_for(@new_post) do |builder|
allow(builder).to receive(:country_select).and_return("<select><option>...</option></select>".html_safe)
concat(builder.input(:country, :as => :country))
end)
end
it_should_have_input_wrapper_with_class("country")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_country_input")
# TODO -- needs stubbing inside the builder block, tricky!
#it_should_apply_error_logic_for_input_type(:country)
it 'should generate a label for the input' do
expect(output_buffer.to_str).to have_tag('form li label')
expect(output_buffer.to_str).to have_tag('form li label[@for="post_country"]')
expect(output_buffer.to_str).to have_tag('form li label', :text => /Country/)
end
it "should generate a select" do
expect(output_buffer.to_str).to have_tag("form li select")
end
end
describe ":priority_countries option" do
it "should be passed down to the country_select helper when provided" do
priority_countries = ["Foo", "Bah"]
semantic_form_for(@new_post) do |builder|
allow(builder).to receive(:country_select).and_return("<select><option>...</option></select>".html_safe)
expect(builder).to receive(:country_select).with(:country, { :priority_countries => priority_countries }, {:id => "post_country", :required => false, :autofocus => false, :readonly => false}).and_return("<select><option>...</option></select>".html_safe)
concat(builder.input(:country, :as => :country, :priority_countries => priority_countries))
end
end
it "should default to the @@priority_countries config when absent" do
priority_countries = Formtastic::FormBuilder.priority_countries
expect(priority_countries).not_to be_empty
expect(priority_countries).not_to be_nil
semantic_form_for(@new_post) do |builder|
allow(builder).to receive(:country_select).and_return("<select><option>...</option></select>".html_safe)
expect(builder).to receive(:country_select).with(:country, { :priority_countries => priority_countries }, {:id => "post_country", :required => false, :autofocus => false, :readonly => false}).and_return("<select><option>...</option></select>".html_safe)
concat(builder.input(:country, :as => :country))
end
end
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
allow(builder).to receive(:country_select).and_return("<select><option>...</option></select>".html_safe)
expect(builder).to receive(:country_select).with(:country, { :priority_countries => [] }, {:id => "context2_post_country", :required => false, :autofocus => false, :readonly => false}).and_return("<select><option>...</option></select>".html_safe)
concat(builder.input(:country, :priority_countries => []))
end)
end
it_should_have_input_wrapper_with_id("context2_post_country_input")
it_should_have_label_for("context2_post_country")
end
describe "matching" do
describe "when the attribute is 'country'" do
before do
concat(semantic_form_for(@new_post) do |builder|
allow(builder).to receive(:country_select).and_return("<select><option>...</option></select>".html_safe)
concat(builder.input(:country))
end)
end
it "should render a country input" do
expect(output_buffer.to_str).to have_tag "form li.country"
end
end
describe "when the attribute is 'country_something'" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:country_subdivision))
concat(builder.input(:country_code))
end)
end
it "should render a country input" do
expect(output_buffer.to_str).not_to have_tag "form li.country"
expect(output_buffer.to_str).to have_tag "form li.string", :count => 2
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/phone_input_spec.rb | spec/inputs/phone_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'phone input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:phone))
end)
end
it_should_have_input_wrapper_with_class(:phone)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_phone_input")
it_should_have_label_with_text(/Phone/)
it_should_have_label_for("post_phone")
it_should_have_input_with_id("post_phone")
it_should_have_input_with_type(:tel)
it_should_have_input_with_name("post[phone]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:phone))
end)
end
it_should_have_input_wrapper_with_id("context2_post_phone_input")
it_should_have_label_and_input_with_id("context2_post_phone")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :phone))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :phone, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/include_blank_spec.rb | spec/inputs/include_blank_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe "*select: options[:include_blank]" do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
allow(@new_post).to receive(:author_id).and_return(nil)
allow(@new_post).to receive(:publish_at).and_return(nil)
end
SELECT_INPUT_TYPES = {
:select => :author,
:datetime_select => :publish_at,
:date_select => :publish_at,
:time_select => :publish_at
}
SELECT_INPUT_TYPES.each do |as, attribute|
describe "for #{as} input" do
describe 'when :include_blank is not set' do
it 'blank value should be included if the default value specified in config is true' do
Formtastic::FormBuilder.include_blank_for_select_by_default = true
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(attribute, :as => as))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']", "")
end
it 'blank value should not be included if the default value specified in config is false' do
Formtastic::FormBuilder.include_blank_for_select_by_default = false
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(attribute, :as => as))
end)
expect(output_buffer.to_str).not_to have_tag("form li select option[@value='']", "")
end
after do
Formtastic::FormBuilder.include_blank_for_select_by_default = true
end
end
describe 'when :include_blank is set to false' do
it 'should not have a blank option' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(attribute, :as => as, :include_blank => false))
end)
expect(output_buffer.to_str).not_to have_tag("form li select option[@value='']", "")
end
end
describe 'when :include_blank is set to true' do
it 'should have a blank select option' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(attribute, :as => as, :include_blank => true))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']", "")
end
end
if as == :select
describe 'when :include_blank is set to a string' do
it 'should have a select option with blank value but that string as text' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(attribute, :as => as, :include_blank => 'string'))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']", "string")
end
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/check_boxes_input_spec.rb | spec/inputs/check_boxes_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'check_boxes input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'for a has_many association' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :value_as_class => true, :required => true))
end)
end
it_should_have_input_wrapper_with_class("check_boxes")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("author_posts_input")
it_should_have_a_nested_fieldset
it_should_have_a_nested_fieldset_with_class('choices')
it_should_have_a_nested_ordered_list_with_class('choices-group')
it_should_apply_error_logic_for_input_type(:check_boxes)
it_should_call_find_on_association_class_when_no_collection_is_provided(:check_boxes)
it_should_use_the_collection_when_provided(:check_boxes, 'input[@type="checkbox"]')
it 'should generate a legend containing a label with text for the input' do
expect(output_buffer.to_str).to have_tag('form li fieldset legend.label label')
expect(output_buffer.to_str).to have_tag('form li fieldset legend.label label', :text => /Posts/)
end
it 'should not link the label within the legend to any input' do
expect(output_buffer.to_str).not_to have_tag('form li fieldset legend label[@for^="author_post_ids_"]')
end
it 'should generate an ordered list with an li.choice for each choice' do
expect(output_buffer.to_str).to have_tag('form li fieldset ol')
expect(output_buffer.to_str).to have_tag('form li fieldset ol li.choice input[@type=checkbox]', :count => ::Post.all.size)
end
it 'should have one option with a "checked" attribute' do
expect(output_buffer.to_str).to have_tag('form li input[@checked]', :count => 1)
end
it 'should not generate hidden inputs with default value blank' do
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li label input[@type='hidden'][@value='']")
end
it 'should not render hidden inputs inside the ol' do
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li input[@type='hidden']")
end
it 'should render one hidden input for each choice outside the ol' do
expect(output_buffer.to_str).to have_tag("form li fieldset > input[@type='hidden']", :count => 1)
end
describe "each choice" do
it 'should not give the choice label the .label class' do
expect(output_buffer.to_str).not_to have_tag('li.choice label.label')
end
it 'should not be marked as required' do
expect(output_buffer.to_str).not_to have_tag('li.choice input[@required]')
end
it 'should contain a label for the radio input with a nested input and label text' do
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /#{post.to_label}/)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='author_post_ids_#{post.id}']")
end
end
it 'should use values as li.class when value_as_class is true' do
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li.post_#{post.id} label")
end
end
it 'should have a checkbox input but no hidden field for each post' do
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#author_post_ids_#{post.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='author[post_ids][]']", :count => 1)
end
end
it 'should have a hidden field with an empty array value for the collection to allow clearing of all checkboxes' do
expect(output_buffer.to_str).to have_tag("form li fieldset > input[@type=hidden][@name='author[post_ids][]'][@value='']", :count => 1)
end
it 'the hidden field with an empty array value should be followed by the ol' do
expect(output_buffer.to_str).to have_tag("form li fieldset > input[@type=hidden][@name='author[post_ids][]'][@value=''] + ol", :count => 1)
end
it 'should not have a hidden field with an empty string value for the collection' do
expect(output_buffer.to_str).not_to have_tag("form li fieldset > input[@type=hidden][@name='author[post_ids]'][@value='']", :count => 1)
end
it 'should have a checkbox and a hidden field for each post with :hidden_field => true' do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :hidden_fields => true, :value_as_class => true))
end)
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#author_post_ids_#{post.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='author[post_ids][]']", :count => 2)
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /#{post.to_label}/)
end
end
it "should mark input as checked if it's the the existing choice" do
expect(::Post.all.include?(@fred.posts.first)).to be_truthy
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@checked='checked']")
end
end
describe 'and no object is given' do
before(:example) do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :check_boxes, :collection => ::Author.all))
end)
end
it 'should generate a fieldset with legend' do
expect(output_buffer.to_str).to have_tag('form li fieldset legend', :text => /Author/)
end
it 'shold generate an li tag for each item in the collection' do
expect(output_buffer.to_str).to have_tag('form li fieldset ol li input[@type=checkbox]', :count => ::Author.all.size)
end
it 'should generate labels for each item' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /#{author.to_label}/)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']")
end
end
it 'should generate inputs for each item' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#project_author_id_#{author.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@type='checkbox']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='#{author.id}']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='project[author_id][]']")
end
end
it 'should html escape the label string' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :check_boxes, :collection => [["<b>Item 1</b>", 1], ["<b>Item 2</b>", 2]]))
end)
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', text: %r{<b>Item [12]</b>}, count: 2) do |label|
expect(label).to have_text('<b>Item 1</b>', count: 1)
expect(label).to have_text('<b>Item 2</b>', count: 1)
end
end
end
describe 'when :hidden_fields is set to false' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :value_as_class => true, :hidden_fields => false))
end)
end
it 'should have a checkbox input for each post' do
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input#author_post_ids_#{post.id}")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@name='author[post_ids][]']", :count => ::Post.all.length)
end
end
it "should mark input as checked if it's the the existing choice" do
expect(::Post.all.include?(@fred.posts.first)).to be_truthy
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@checked='checked']")
end
it 'should not generate empty hidden inputs' do
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li label input[@type='hidden'][@value='']", :count => ::Post.all.length)
end
end
describe 'when :disabled is set' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
end
describe "no disabled items" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :disabled => nil))
end)
end
it 'should not have any disabled item(s)' do
expect(output_buffer.to_str).not_to have_tag("form li fieldset ol li label input[@disabled='disabled']")
end
end
describe "single disabled item" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :disabled => @fred.id))
end)
end
it "should have one item disabled; the specified one" do
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@disabled='disabled']", :count => 1)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_ids_#{@fred.id}']", :text => /fred/i)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@disabled='disabled'][@value='#{@fred.id}']")
end
end
describe "multiple disabled items" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :disabled => [@bob.id, @fred.id]))
end)
end
it "should have multiple items disabled; the specified ones" do
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@disabled='disabled']", :count => 2)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_ids_#{@bob.id}']", :text => /bob/i)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@disabled='disabled'][@value='#{@bob.id}']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_author_ids_#{@fred.id}']", :text => /fred/i)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@disabled='disabled'][@value='#{@fred.id}']")
end
end
end
describe "with i18n of the legend label" do
before do
::I18n.backend.store_translations :en, :formtastic => { :labels => { :post => { :authors => "Translated!" }}}
with_config :i18n_lookups_by_default, true do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes))
end)
end
end
after do
::I18n.backend.reload!
end
it "should do foo" do
expect(output_buffer.to_str).to have_tag("legend.label label", :text => /Translated/)
end
end
describe "when :label option is set" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :label => 'The authors'))
end)
end
it "should output the correct label title" do
expect(output_buffer.to_str).to have_tag("legend.label label", :text => /The authors/)
end
end
describe "when :label option is false" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :label => false))
end)
end
it "should not output the legend" do
expect(output_buffer.to_str).not_to have_tag("legend.label")
end
it "should not cause escaped HTML" do
expect(output_buffer.to_str).not_to include(">")
end
end
describe "when :required option is true" do
before do
allow(@new_post).to receive(:author_ids).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes, :required => true))
end)
end
it "should output the correct label title" do
expect(output_buffer.to_str).to have_tag("legend.label label abbr")
end
end
end
describe 'for a enum column' do
before do
allow(@new_post).to receive(:status) { 'inactive' }
statuses = ActiveSupport::HashWithIndifferentAccess.new("active"=>0, "inactive"=>1)
allow(@new_post.class).to receive(:statuses) { statuses }
allow(@new_post).to receive(:defined_enums) { { "status" => statuses } }
end
it 'should have a select inside the wrapper' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:status, :as => :check_boxes))
end)
}.to raise_error(Formtastic::UnsupportedEnumCollection)
end
end
describe 'for a has_and_belongs_to_many association' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, :as => :check_boxes))
end)
end
it 'should render checkboxes' do
# I'm aware these two lines test the same thing
expect(output_buffer.to_str).to have_tag('input[type="checkbox"]', :count => 2)
expect(output_buffer.to_str).to have_tag('input[type="checkbox"]', :count => ::Author.all.size)
end
it 'should only select checkboxes that are present in the association' do
# I'm aware these two lines test the same thing
expect(output_buffer.to_str).to have_tag('input[checked="checked"]', :count => 1)
expect(output_buffer.to_str).to have_tag('input[checked="checked"]', :count => @freds_post.authors.size)
end
end
describe ':collection for a has_and_belongs_to_many association' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, as: :check_boxes, collection: Author.all))
end)
end
it 'should render checkboxes' do
# I'm aware these two lines test the same thing
expect(output_buffer.to_str).to have_tag('input[type="checkbox"]', :count => 2)
expect(output_buffer.to_str).to have_tag('input[type="checkbox"]', :count => ::Author.all.size)
end
it 'should only select checkboxes that are present in the association' do
# I'm aware these two lines test the same thing
expect(output_buffer.to_str).to have_tag('input[checked="checked"]', :count => 1)
expect(output_buffer.to_str).to have_tag('input[checked="checked"]', :count => @freds_post.authors.size)
end
end
describe 'for an association when a :collection is provided' do
describe 'it should use the specified :member_value option' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'to set the right input value' do
item = double('item')
expect(item).not_to receive(:id)
allow(item).to receive(:custom_value).and_return('custom_value')
expect(item).to receive(:custom_value).exactly(3).times
expect(@new_post.author).to receive(:custom_value).exactly(1).times
with_deprecation_silenced do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :check_boxes, :member_value => :custom_value, :collection => [item, item, item]))
end)
end
expect(output_buffer.to_str).to have_tag('input[@type=checkbox][@value="custom_value"]', :count => 3)
end
end
end
describe 'when :collection is provided as an array of arrays' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
allow(@fred).to receive(:genres) { ['fiction', 'biography'] }
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:genres, :as => :check_boxes, :collection => [['Fiction', 'fiction'], ['Non-fiction', 'non_fiction'], ['Biography', 'biography']]))
end)
end
it 'should check the correct checkboxes' do
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='fiction'][@checked='checked']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='biography'][@checked='checked']")
end
end
describe 'when :collection is a set' do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
allow(@fred).to receive(:roles) { Set.new([:reviewer, :admin]) }
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:roles, :as => :check_boxes, :collection => [['User', :user], ['Reviewer', :reviewer], ['Administrator', :admin]]))
end)
end
it 'should check the correct checkboxes' do
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='user']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='admin'][@checked='checked']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label input[@value='reviewer'][@checked='checked']")
end
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@fred, :namespace => "context2") do |builder|
concat(builder.input(:posts, :as => :check_boxes))
end)
end
it "should have a label for #context2_author_post_ids_19" do
expect(output_buffer.to_str).to have_tag("form li label[@for='context2_author_post_ids_19']")
end
it_should_have_input_with_id('context2_author_post_ids_19')
it_should_have_input_wrapper_with_id("context2_author_posts_input")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@fred) do |builder|
concat(builder.fields_for(@fred.posts.first, :index => 3) do |author|
concat(author.input(:authors, :as => :check_boxes))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#author_post_3_authors_input")
end
it 'should index the id of the input tag' do
expect(output_buffer.to_str).to have_tag("input#author_post_3_author_ids_42")
end
it 'should index the name of the checkbox input' do
expect(output_buffer.to_str).to have_tag("input[@type='checkbox'][@name='author[post][3][author_ids][]']")
end
end
describe "when collection is an array" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
@_collection = [["First", 1], ["Second", 2]]
mock_everything
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :collection => @_collection))
end)
end
it "should use array items for labels and values" do
@_collection.each do |post|
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /#{post.first}/)
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='author_post_ids_#{post.last}']")
end
end
it "should not check any items" do
expect(output_buffer.to_str).not_to have_tag('form li input[@checked]')
end
describe "and the attribute has values" do
before do
allow(@fred).to receive(:posts) { [1] }
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :collection => @_collection))
end)
end
it "should check the appropriate items" do
expect(output_buffer.to_str).to have_tag("form li input[@value='1'][@checked]")
end
end
describe "and the collection includes html options" do
before do
@_collection = [["First", 1, {'data-test' => 'test-data'}], ["Second", 2, {'data-test2' => 'test-data2'}]]
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :collection => @_collection))
end)
end
it "should have injected the html attributes" do
@_collection.each do |v|
expect(output_buffer.to_str).to have_tag("form li input[@value='#{v[1]}'][@#{v[2].keys[0]}='#{v[2].values[0]}']")
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/select_input_spec.rb | spec/inputs/select_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'select input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'explicit values' do
describe 'using an array of values' do
before do
@array_with_values = ["Title A", "Title B", "Title C"]
@array_with_keys_and_values = [["Title D", 1], ["Title E", 2], ["Title F", 3]]
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :select, :collection => @array_with_values))
concat(builder.input(:title, :as => :select, :collection => @array_with_keys_and_values))
end)
end
it 'should have a option for each key and/or value' do
@array_with_values.each do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v}']", :text => /^#{v}$/)
end
@array_with_keys_and_values.each do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v.second}']", :text => /^#{v.first}$/)
end
end
end
describe 'using a set of values' do
before do
@set_with_values = Set.new(["Title A", "Title B", "Title C"])
@set_with_keys_and_values = [["Title D", :d], ["Title E", :e], ["Title F", :f]]
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :select, :collection => @set_with_values))
concat(builder.input(:title, :as => :select, :collection => @set_with_keys_and_values))
end)
end
it 'should have a option for each key and/or value' do
@set_with_values.each do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v}']", :text => /^#{v}$/)
end
@set_with_keys_and_values.each do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v.second}']", :text => /^#{v.first}$/)
end
end
end
describe "using a related model without reflection's options (Mongoid Document)" do
before do
allow(@new_post).to receive(:mongoid_reviewer)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:mongoid_reviewer, :as => :select))
end)
end
it 'should draw select options' do
expect(output_buffer.to_str).to have_tag('form li select')
expect(output_buffer.to_str).to have_tag('form li select#post_reviewer_id')
expect(output_buffer.to_str).not_to have_tag('form li select#post_mongoid_reviewer_id')
end
end
describe 'using a range' do
before do
@range_with_values = 1..5
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :select, :collection => @range_with_values))
end)
end
it 'should have an option for each value' do
@range_with_values.each do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v}']", :text => /^#{v}$/)
end
end
end
describe 'using a string' do
before do
@string ="<option value='0'>0</option><option value='1'>1</option>".html_safe
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :select, :collection => @string))
end)
end
it 'should render select options using provided HTML string' do
2.times do |v|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{v}']", :text => /^#{v}$/)
end
end
end
describe 'using a nil name' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :select, :collection => [], :input_html => {:name => nil}))
end)
end
it_should_have_select_with_name("post[title]")
end
end
describe 'for boolean columns' do
describe 'default formtastic locale' do
before do
# Note: Works, but something like Formtastic.root.join(...) would probably be "safer".
::I18n.load_path = [File.join(File.dirname(__FILE__), *%w[.. .. lib locale en.yml])]
::I18n.backend.send(:init_translations)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:published, :as => :select))
end)
end
after do
::I18n.load_path = []
::I18n.backend.store_translations :en, {}
end
it 'should render a select with at least options: true/false' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='true']", :text => /^Yes$/)
expect(output_buffer.to_str).to have_tag("form li select option[@value='false']", :text => /^No$/)
end
end
describe 'custom locale' do
before do
@boolean_select_labels = {:yes => 'Yep', :no => 'Nope'}
::I18n.backend.store_translations :en, :formtastic => @boolean_select_labels
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:published, :as => :select))
end)
end
after do
::I18n.backend.store_translations :en, {}
end
it 'should render a select with at least options: true/false' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='true']", :text => /#{@boolean_select_labels[:yes]}/)
expect(output_buffer.to_str).to have_tag("form li select option[@value='false']", :text => /#{@boolean_select_labels[:no]}/)
end
end
end
describe 'for a enum column' do
before do
allow(@new_post).to receive(:status) { 'inactive' }
statuses = ActiveSupport::HashWithIndifferentAccess.new("active"=>0, "inactive"=>1)
allow(@new_post.class).to receive(:statuses) { statuses }
allow(@new_post).to receive(:defined_enums) { { "status" => statuses } }
end
context 'with translations in a nested association input' do
before do
::I18n.backend.store_translations :en, activerecord: {
attributes: {
post: {
statuses: {
active: 'I am active',
inactive: 'I am inactive'
}
}
}
}
allow(@fred).to receive(:posts).and_return([@new_post])
concat(semantic_form_for(@fred) do |builder|
concat(builder.inputs(for: @fred.posts.first) do |nested_builder|
nested_builder.input(:status, as: :select)
end)
end)
end
after do
::I18n.backend.reload!
end
it 'should use localized enum values' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='active']", text: 'I am active')
expect(output_buffer.to_str).to have_tag("form li select option[@value='inactive']", text: 'I am inactive')
end
end
context 'single choice' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:status, :as => :select))
end)
end
it_should_have_input_wrapper_with_class("select")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_status_input")
it_should_have_label_with_text(/Status/)
it_should_have_label_for('post_status')
it_should_apply_error_logic_for_input_type(:select)
it 'should have a select inside the wrapper' do
expect(output_buffer.to_str).to have_tag('form li select')
expect(output_buffer.to_str).to have_tag('form li select#post_status')
end
it 'should have a valid name' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[status]']")
expect(output_buffer.to_str).not_to have_tag("form li select[@name='post[status][]']")
end
it 'should not create a multi-select' do
expect(output_buffer.to_str).not_to have_tag('form li select[@multiple]')
end
it 'should not add a hidden input' do
expect(output_buffer.to_str).not_to have_tag('form li input[@type="hidden"]')
end
it 'should create a select without size' do
expect(output_buffer.to_str).not_to have_tag('form li select[@size]')
end
it 'should have a blank option' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should have a select option for each defined enum status' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[status]'] option", :count => @new_post.class.statuses.count + 1)
@new_post.class.statuses.each do |label, value|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{label}']", :text => /#{label.humanize}/)
end
end
it 'should have one option with a "selected" attribute (TODO)' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[status]'] option[@selected]", :count => 1)
end
end
context 'multiple choice' do
it 'raises an error' do
expect {
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:status, :as => :select, :multiple => true))
end)
}.to raise_error Formtastic::UnsupportedEnumCollection
end
end
end
describe 'for a belongs_to association' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select))
concat(builder.input(:reviewer, :as => :select))
end)
end
it_should_have_input_wrapper_with_class("select")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_author_input")
it_should_have_label_with_text(/Author/)
it_should_have_label_for('post_author_id')
it_should_apply_error_logic_for_input_type(:select)
it_should_call_find_on_association_class_when_no_collection_is_provided(:select)
it_should_use_the_collection_when_provided(:select, 'option')
it 'should have a select inside the wrapper' do
expect(output_buffer.to_str).to have_tag('form li select')
expect(output_buffer.to_str).to have_tag('form li select#post_author_id')
expect(output_buffer.to_str).to have_tag('form li select#post_reviewer_id')
end
it 'should have a valid name' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[author_id]']")
expect(output_buffer.to_str).not_to have_tag("form li select[@name='post[author_id][]']")
expect(output_buffer.to_str).not_to have_tag("form li select[@name='post[reviewer_id][]']")
end
it 'should not create a multi-select' do
expect(output_buffer.to_str).not_to have_tag('form li select[@multiple]')
end
it 'should not add a hidden input' do
expect(output_buffer.to_str).not_to have_tag('form li input[@type="hidden"]')
end
it 'should create a select without size' do
expect(output_buffer.to_str).not_to have_tag('form li select[@size]')
end
it 'should have a blank option' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should have a select option for each Author' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[author_id]'] option", :count => ::Author.all.size + 1)
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{author.id}']", :text => /#{author.to_label}/)
end
end
it 'should have one option with a "selected" attribute (bob)' do
expect(output_buffer.to_str).to have_tag("form li select[@name='post[author_id]'] option[@selected]", :count => 1)
end
it 'should not singularize the association name' do
allow(@new_post).to receive(:author_status).and_return(@bob)
allow(@new_post).to receive(:author_status_id).and_return(@bob.id)
allow(@new_post).to receive(:column_for_attribute).and_return(double('column', :type => :integer, :limit => 255))
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author_status, :as => :select))
end)
expect(output_buffer.to_str).to have_tag('form li select#post_author_status_id')
end
end
describe "for a belongs_to association with :conditions" do
before do
allow(::Post).to receive(:reflect_on_association).with(:author) do
mock = double('reflection', :scope => nil, :options => {:conditions => {:active => true}}, :klass => ::Author, :macro => :belongs_to)
allow(mock).to receive(:[]).with(:class_name).and_return("Author")
mock
end
end
it "should call author.where with association conditions" do
expect(::Author).to receive(:where).with({:active => true})
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select))
end
end
end
describe "for a belongs_to association with scope" do
before do
@active_scope = -> { active }
allow(::Post).to receive(:reflect_on_association).with(:author) do
mock = double('reflection', :scope => @active_scope, options: {}, :klass => ::Author, :macro => :belongs_to)
allow(mock).to receive(:[]).with(:class_name).and_return("Author")
mock
end
end
it "should call author.merge with association scope" do
expect(::Author).to receive(:merge).with(@active_scope)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select))
end
end
end
describe 'for a has_many association' do
before do
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :select))
end)
end
it_should_have_input_wrapper_with_class("select")
it_should_have_input_wrapper_with_id("author_posts_input")
it_should_have_label_with_text(/Post/)
it_should_have_label_for('author_post_ids')
it_should_apply_error_logic_for_input_type(:select)
it_should_call_find_on_association_class_when_no_collection_is_provided(:select)
it_should_use_the_collection_when_provided(:select, 'option')
it 'should have a select inside the wrapper' do
expect(output_buffer.to_str).to have_tag('form li select')
expect(output_buffer.to_str).to have_tag('form li select#author_post_ids')
end
it 'should have a multi-select select' do
expect(output_buffer.to_str).to have_tag('form li select[@multiple="multiple"]')
end
it 'should append [] to the name attribute for multiple select' do
expect(output_buffer.to_str).to have_tag('form li select[@multiple="multiple"][@name="author[post_ids][]"]')
end
it 'should have a hidden field' do
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"][@name="author[post_ids][]"]', :count => 1)
end
it 'should have a select option for each Post' do
expect(output_buffer.to_str).to have_tag('form li select option', :count => ::Post.all.size)
::Post.all.each do |post|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{post.id}']", :text => /#{post.to_label}/)
end
end
it 'should not have a blank option by default' do
expect(output_buffer.to_str).not_to have_tag("form li select option[@value='']")
end
it 'should respect the :include_blank option for single selects' do
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :select, :multiple => false, :include_blank => true))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should respect the :include_blank option for multiple selects' do
concat(semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :select, :multiple => true, :include_blank => true))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should have one option with a "selected" attribute' do
expect(output_buffer.to_str).to have_tag('form li select option[@selected]', :count => 1)
end
end
describe 'for a has_and_belongs_to_many association' do
before do
concat(semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, :as => :select))
end)
end
it_should_have_input_wrapper_with_class("select")
it_should_have_input_wrapper_with_id("post_authors_input")
it_should_have_label_with_text(/Author/)
it_should_have_label_for('post_author_ids')
it_should_apply_error_logic_for_input_type(:select)
it_should_call_find_on_association_class_when_no_collection_is_provided(:select)
it_should_use_the_collection_when_provided(:select, 'option')
it 'should have a select inside the wrapper' do
expect(output_buffer.to_str).to have_tag('form li select')
expect(output_buffer.to_str).to have_tag('form li select#post_author_ids')
end
it 'should have a multi-select select' do
expect(output_buffer.to_str).to have_tag('form li select[@multiple="multiple"]')
end
it 'should have a select option for each Author' do
expect(output_buffer.to_str).to have_tag('form li select option', :count => ::Author.all.size)
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{author.id}']", :text => /#{author.to_label}/)
end
end
it 'should not have a blank option by default' do
expect(output_buffer.to_str).not_to have_tag("form li select option[@value='']")
end
it 'should respect the :include_blank option for single selects' do
concat(semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, :as => :select, :multiple => false, :include_blank => true))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should respect the :include_blank option for multiple selects' do
concat(semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, :as => :select, :multiple => true, :include_blank => true))
end)
expect(output_buffer.to_str).to have_tag("form li select option[@value='']")
end
it 'should have one option with a "selected" attribute' do
expect(output_buffer.to_str).to have_tag('form li select option[@selected]', :count => 1)
end
end
describe 'when :prompt => "choose something" is set' do
before do
allow(@new_post).to receive(:author_id).and_return(nil)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select, :prompt => "choose author"))
end)
end
it 'should have a select with prompt' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='']", :text => /choose author/, :count => 1)
end
it 'should not have a second blank select option' do
expect(output_buffer.to_str).to have_tag("form li select option[@value='']", :count => 1)
end
end
describe 'when no object is given' do
before(:example) do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author, :as => :select, :collection => ::Author.all))
end)
end
it 'should generate label' do
expect(output_buffer.to_str).to have_tag('form li label', :text => /Author/)
expect(output_buffer.to_str).to have_tag("form li label[@for='project_author']")
end
it 'should generate select inputs' do
expect(output_buffer.to_str).to have_tag('form li select#project_author')
expect(output_buffer.to_str).to have_tag('form li select option', :count => ::Author.all.size + 1)
end
it 'should generate an option to each item' do
::Author.all.each do |author|
expect(output_buffer.to_str).to have_tag("form li select option[@value='#{author.id}']", :text => /#{author.to_label}/)
end
end
end
describe 'when no association exists' do
it 'should still generate a valid name attribute' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_name, :as => :select, :collection => ::Author.all))
end)
expect(output_buffer.to_str).to have_tag("form li select[@name='project[author_name]']")
end
describe 'and :multiple is set to true through :input_html' do
it "should make the select a multi-select" do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_name, :as => :select, :input_html => {:multiple => true} ))
end)
expect(output_buffer.to_str).to have_tag("form li select[@multiple]")
end
end
describe 'and :multiple is set to true' do
it "should make the select a multi-select" do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_name, :as => :select, :multiple => true, :collection => ["Fred", "Bob"]))
end)
expect(output_buffer.to_str).to have_tag("form li select[@multiple]")
end
end
end
describe 'when a grouped collection collection is given' do
before(:example) do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
@grouped_opts = [['one', ['pencil', 'crayon', 'pen']],
['two', ['eyes', 'hands', 'feet']],
['three', ['wickets', 'witches', 'blind mice']]]
concat(builder.input(:author, :as => :select, :collection => grouped_options_for_select(@grouped_opts, "hands")))
end)
end
it 'should generate an option to each item' do
@grouped_opts.each do |opt_pair|
expect(output_buffer.to_str).to have_tag("form li select optgroup[@label='#{opt_pair[0]}']")
opt_pair[1].each do |v|
expect(output_buffer.to_str).to have_tag("form li select optgroup[@label='#{opt_pair[0]}'] option[@value='#{v}']")
end
end
expect(output_buffer.to_str).to have_tag("form li select optgroup option[@selected]","hands")
end
end
describe "enum" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
@some_meta_descriptions = ["One", "Two", "Three"]
allow(@new_post).to receive(:meta_description).at_least(:once)
end
describe ":as is not set" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:meta_description, :collection => @some_meta_descriptions))
end)
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:meta_description, :collection => @some_meta_descriptions))
end)
end
it "should render a select field" do
expect(output_buffer.to_str).to have_tag("form li select", :count => 2)
end
end
describe ":as is set" do
before do
# Should not be a case, but just checking :as got highest priority in setting input type.
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:meta_description, :as => :string, :collection => @some_meta_descriptions))
end)
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:meta_description, :as => :string, :collection => @some_meta_descriptions))
end)
end
it "should render a text field" do
expect(output_buffer.to_str).to have_tag("form li input[@type='text']", :count => 2)
end
end
end
describe 'when a namespace is provided' do
before do
concat(semantic_form_for(@freds_post, :namespace => 'context2') do |builder|
concat(builder.input(:authors, :as => :select))
end)
end
it_should_have_input_wrapper_with_id("context2_post_authors_input")
it_should_have_select_with_id("context2_post_author_ids")
it_should_have_label_for("context2_post_author_ids")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :select))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_name")
end
it 'should index the name of the select' do
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][name]']")
end
end
context "when required" do
it "should add the required attribute to the select's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select, :required => true))
end)
expect(output_buffer.to_str).to have_tag("select[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/boolean_input_spec.rb | spec/inputs/boolean_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'boolean input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe 'generic' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean))
end)
end
it_should_have_input_wrapper_with_class("boolean")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_allow_comments_input")
it_should_apply_error_logic_for_input_type(:boolean)
it 'should generate a label containing the input' do
expect(output_buffer.to_str).not_to have_tag('label.label')
expect(output_buffer.to_str).to have_tag('form li label', :count => 1)
expect(output_buffer.to_str).to have_tag('form li label[@for="post_allow_comments"]')
expect(output_buffer.to_str).to have_tag('form li label', :text => /Allow comments/)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"]', :count => 1)
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"]', :count => 1)
expect(output_buffer.to_str).not_to have_tag('form li label input[@type="hidden"]', :count => 1) # invalid HTML5
end
it 'should not add a "name" attribute to the label' do
expect(output_buffer.to_str).not_to have_tag('form li label[@name]')
end
it 'should generate a checkbox input' do
expect(output_buffer.to_str).to have_tag('form li label input')
expect(output_buffer.to_str).to have_tag('form li label input#post_allow_comments')
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"]')
expect(output_buffer.to_str).to have_tag('form li label input[@name="post[allow_comments]"]')
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="1"]')
end
it 'should generate a checked input if object.method returns true' do
expect(output_buffer.to_str).to have_tag('form li label input[@checked="checked"]')
expect(output_buffer.to_str).to have_tag('form li input[@name="post[allow_comments]"]', :count => 2)
expect(output_buffer.to_str).to have_tag('form li input#post_allow_comments', :count => 1)
end
end
it 'should generate a checked input if :input_html is passed :checked => checked' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:answer_comments, :as => :boolean, :input_html => {:checked => 'checked'}))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@checked="checked"]')
end
it 'should name the hidden input with the :name html_option' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:answer_comments, :as => :boolean, :input_html => { :name => "foo" }))
end)
expect(output_buffer.to_str).to have_tag('form li input[@type="checkbox"][@name="foo"]', :count => 1)
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"][@name="foo"]', :count => 1)
end
it 'should name the hidden input with the :name html_option' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:answer_comments, :as => :boolean, :input_html => { :name => "foo" }))
end)
expect(output_buffer.to_str).to have_tag('form li input[@type="checkbox"][@name="foo"]', :count => 1)
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"][@name="foo"]', :count => 1)
end
it "should generate a disabled input and hidden input if :input_html is passed :disabled => 'disabled' " do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :input_html => {:disabled => 'disabled'}))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@disabled="disabled"]', :count => 1)
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"][@disabled="disabled"]', :count => 1)
end
it 'should generate an input[id] with matching label[for] when id passed in :input_html' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :input_html => {:id => 'custom_id'}))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@id="custom_id"]')
expect(output_buffer.to_str).to have_tag('form li label[@for="custom_id"]')
end
it 'should allow checked and unchecked values to be sent' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'checked', :unchecked_value => 'unchecked'))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="checked"]:not([@unchecked_value][@checked_value])')
expect(output_buffer.to_str).to have_tag('form li input[@type="hidden"][@value="unchecked"]')
expect(output_buffer.to_str).not_to have_tag('form li label input[@type="hidden"]') # invalid HTML5
end
it 'should generate a checked input if object.method returns checked value' do
allow(@new_post).to receive(:allow_comments).and_return('yes')
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="yes"][@checked="checked"]')
end
it 'should not generate a checked input if object.method returns unchecked value' do
allow(@new_post).to receive(:allow_comments).and_return('no')
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="yes"]:not([@checked])')
end
it 'should generate a checked input if object.method returns checked value' do
allow(@new_post).to receive(:allow_comments).and_return('yes')
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="yes"][@checked="checked"]')
end
it 'should generate a checked input for boolean database values compared to string checked values' do
allow(@new_post).to receive(:foo).and_return(1)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:foo, :as => :boolean))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="1"][@checked="checked"]')
end
it 'should generate a checked input if object.method returns checked value when inverted' do
allow(@new_post).to receive(:allow_comments).and_return(0)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 0, :unchecked_value => 1))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="0"][@checked="checked"]')
end
it 'should not generate a checked input if object.method returns unchecked value' do
allow(@new_post).to receive(:allow_comments).and_return('no')
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'yes', :unchecked_value => 'no'))
end)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"][@value="yes"]:not([@checked])')
end
it 'should generate a label and a checkbox even if no object is given' do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:allow_comments, :as => :boolean))
end)
expect(output_buffer.to_str).to have_tag('form li label[@for="project_allow_comments"]')
expect(output_buffer.to_str).to have_tag('form li label', :text => /Allow comments/)
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"]')
expect(output_buffer.to_str).to have_tag('form li label input#project_allow_comments')
expect(output_buffer.to_str).to have_tag('form li label input[@type="checkbox"]')
expect(output_buffer.to_str).to have_tag('form li label input[@name="project[allow_comments]"]')
end
it 'should not pass input_html options down to the label html' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :boolean, :input_html => { :tabindex => 2, :x => "X" })
end)
expect(output_buffer.to_str).not_to have_tag('label[tabindex]')
expect(output_buffer.to_str).not_to have_tag('label[x]')
end
context "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :boolean, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
it "should not add the required attribute to the boolean fields input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :boolean))
end)
expect(output_buffer.to_str).not_to have_tag("input[@required]")
end
end
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:allow_comments, :as => :boolean))
end)
end
it_should_have_input_wrapper_with_id("context2_post_allow_comments_input")
it_should_have_an_inline_label_for("context2_post_allow_comments")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :boolean))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the input tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the hidden input' do
expect(output_buffer.to_str).to have_tag("input[@type='hidden'][@name='post[author_attributes][3][name]']")
end
it 'should index the name of the checkbox input' do
expect(output_buffer.to_str).to have_tag("input[@type='checkbox'][@name='post[author_attributes][3][name]']")
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/color_input_spec.rb | spec/inputs/color_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'color input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:color))
end)
end
it_should_have_input_wrapper_with_class(:color)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_color_input")
it_should_have_label_with_text(/Color/)
it_should_have_label_for("post_color")
it_should_have_input_with_id("post_color")
it_should_have_input_with_type(:color)
it_should_have_input_with_name("post[color]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:color))
end)
end
it_should_have_input_wrapper_with_id("context2_post_color_input")
it_should_have_label_and_input_with_id("context2_post_color")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :color))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :color, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/time_picker_input_spec.rb | spec/inputs/time_picker_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'time_picker input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
context "with an object" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_picker))
end)
end
it_should_have_input_wrapper_with_class(:time_picker)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_label_with_text(/Publish at/)
it_should_have_label_for("post_publish_at")
it_should_have_input_with_id("post_publish_at")
it_should_have_input_with_type(:time)
it_should_have_input_with_name("post[publish_at]")
it_should_apply_custom_input_attributes_when_input_html_provided(:date_picker)
it_should_apply_custom_for_to_label_when_input_html_id_provided(:date_picker)
# TODO why does this blow-up it_should_apply_error_logic_for_input_type(:date_picker)
end
describe "size attribute" do
it "defaults to 5 chars (HH:MM)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[size='5']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :size => '12', :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='12']"
end
end
describe "maxlength attribute" do
it "defaults to 5 chars (HH:MM:SS)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='5']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :maxlength => 12, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='12']"
end
end
describe "value attribute" do
context "when method returns nil" do
it "has no value" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker ))
end
)
expect(output_buffer.to_str).not_to have_tag "li input[value]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :value => "12:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='12:00']"
end
end
context "when method returns a Date" do
before do
@date = Date.new(2000, 11, 11)
allow(@new_post).to receive(:publish_at).and_return(@date)
end
it "renders 00:00" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='00:00']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :value => "23:59" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='23:59']"
end
end
context "when method returns a Time" do
before do
@time = Time.utc(2000,11,11,11,11,11)
allow(@new_post).to receive(:publish_at).and_return(@time)
end
it "renders the time as a HH:MM" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='11:11']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :value => "12:12" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='12:12']"
end
end
context "when method returns an empty String" do
before do
allow(@new_post).to receive(:publish_at).and_return("")
end
it "will be empty" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :value => "12:12:12" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='12:12:12']"
end
end
context "when method returns a String" do
before do
allow(@new_post).to receive(:publish_at).and_return("yeah")
end
it "will be the string" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='yeah']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :value => "12:12:12" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='12:12:12']"
end
end
end
describe "min attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[min]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :min => "13:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[min='13:00']"
end
end
describe "max attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[max]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :max => "13:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[max='13:00']"
end
end
describe "step attribute" do
it "defaults to 60 (seconds)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[step='60']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :step => "3600" }))
end
)
expect(output_buffer.to_str).to have_tag "input[step='3600']"
end
describe "macros" do
before do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :date_picker, :input_html => { :step => step }))
end
)
end
context ":second" do
let(:step) { :second }
it "uses 1" do
expect(output_buffer.to_str).to have_tag "input[step='1']"
end
end
context ":minute" do
let(:step) { :minute }
it "uses 60" do
expect(output_buffer.to_str).to have_tag "input[step='60']"
end
end
context ":fifteen_minutes" do
let(:step) { :fifteen_minutes }
it "uses 900" do
expect(output_buffer.to_str).to have_tag "input[step='900']"
end
end
context ":quarter_hour" do
let(:step) { :quarter_hour }
it "uses 900" do
expect(output_buffer.to_str).to have_tag "input[step='900']"
end
end
context ":thirty_minutes" do
let(:step) { :thirty_minutes }
it "uses 1800" do
expect(output_buffer.to_str).to have_tag "input[step='1800']"
end
end
context ":half_hour" do
let(:step) { :half_hour }
it "uses 1800" do
expect(output_buffer.to_str).to have_tag "input[step='1800']"
end
end
context ":hour" do
let(:step) { :hour }
it "uses 3600" do
expect(output_buffer.to_str).to have_tag "input[step='3600']"
end
end
context ":sixty_minutes" do
let(:step) { :sixty_minutes }
it "uses 3600" do
expect(output_buffer.to_str).to have_tag "input[step='3600']"
end
end
end
end
describe "placeholder attribute" do
it "will be omitted" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[placeholder]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :time_picker, :input_html => { :placeholder => "HH:MM" }))
end
)
expect(output_buffer.to_str).to have_tag "input[placeholder='HH:MM']"
end
context "with i18n set" do
before do
::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :publish_at => 'HH:MM' }}
end
it "can be set with i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_picker))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="HH:MM"]')
end
end
it "can be set with input_html, trumping i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_picker, :input_html => { :placeholder => "Something" }))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="Something"]')
end
end
end
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:publish_at, :as => :time_picker))
end)
end
it_should_have_input_wrapper_with_id("context2_post_publish_at_input")
it_should_have_label_and_input_with_id("context2_post_publish_at")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :time_picker))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_picker, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/datetime_select_input_spec.rb | spec/inputs/datetime_select_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'datetime select input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "general" do
before do
::I18n.backend.store_translations :en, {}
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_select))
end)
end
it_should_have_input_wrapper_with_class("datetime_select")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_a_nested_fieldset
it_should_have_a_nested_fieldset_with_class('fragments')
it_should_have_a_nested_ordered_list_with_class('fragments-group')
it_should_apply_error_logic_for_input_type(:datetime_select)
it 'should have a legend and label with the label text inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label label', :text => /Publish at/)
end
it 'should associate the legend label with the first select' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label')
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label label')
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label label[@for]')
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label label[@for="post_publish_at_1i"]')
end
it 'should have an ordered list of five items inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol.fragments-group')
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li.fragment', :count => 5)
end
it 'should have five labels for year, month and day' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :count => 5)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /year/i)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /month/i)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /day/i)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /hour/i)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /min/i)
end
it 'should have five selects' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li select', :count => 5)
end
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:publish_at, :as => :datetime_select))
end)
end
it_should_have_input_wrapper_with_id("context2_post_publish_at_input")
it_should_have_select_with_id("context2_post_publish_at_1i")
it_should_have_select_with_id("context2_post_publish_at_2i")
it_should_have_select_with_id("context2_post_publish_at_3i")
it_should_have_select_with_id("context2_post_publish_at_4i")
it_should_have_select_with_id("context2_post_publish_at_5i")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :datetime_select))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_1i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_2i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_3i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_4i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_5i")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(1i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(2i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(3i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(4i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(5i)]']")
end
end
describe ':labels option' do
fields = [:year, :month, :day, :hour, :minute]
fields.each do |field|
it "should replace the #{field} label with the specified text if :labels[:#{field}] is set" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :datetime_select, :labels => { field => "another #{field} label" }))
end)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :count => fields.length)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => f == field ? /another #{f} label/i : /#{f}/i)
end
end
it "should not display the label for the #{field} field when :labels[:#{field}] is blank" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :datetime_select, :labels => { field => "" }))
end)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /#{f}/i) unless field == f
end
end
it "should not display the label for the #{field} field when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :datetime_select, :labels => { field => false }))
end)
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset ol li label', :text => /#{f}/i) unless field == f
end
end
it "should not render unsafe HTML when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :datetime_select, :include_seconds => true, :labels => { field => false }))
end)
expect(output_buffer.to_str).not_to include(">")
end
end
it "should not display labels for any fields when :labels is falsy" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :datetime_select, :labels => false))
end)
expect(output_buffer.to_str).not_to have_tag('form li.datetime_select fieldset ol li label')
end
end
describe ":selected option for setting a value" do
it "should set the selected value for the form" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:created_at, :as => :datetime_select, :selected => DateTime.new(2018, 10, 4, 12, 00)))
end
)
expect(output_buffer.to_str).to have_tag "option[value='2018'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='10'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='4'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='12'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='00'][selected='selected']"
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :datetime_select, :required => true))
end)
expect(output_buffer.to_str).to have_tag("select[@required]", :count => 5)
end
end
end
describe "when order does not have year first" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_select, :order => [:day, :month, :year]))
end)
end
it 'should associate the legend label with the new first select' do
expect(output_buffer.to_str).to have_tag('form li.datetime_select fieldset legend.label label[@for="post_publish_at_3i"]')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/with_options_spec.rb | spec/inputs/with_options_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'string input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "with_options and :wrapper_html" do
before do
concat(semantic_form_for(@new_post) do |builder|
builder.with_options :wrapper_html => { :class => ['extra'] } do |opt_builder|
concat(opt_builder.input(:title, :as => :string))
concat(opt_builder.input(:author, :as => :radio))
end
end)
end
it "should have extra class on title" do
expect(output_buffer.to_str).to have_tag("form li#post_title_input.extra")
end
it "should have title as string" do
expect(output_buffer.to_str).to have_tag("form li#post_title_input.string")
end
it "should not have title as radio" do
expect(output_buffer.to_str).not_to have_tag("form li#post_title_input.radio")
end
it "should have extra class on author" do
expect(output_buffer.to_str).to have_tag("form li#post_author_input.extra")
end
it "should not have author as string" do
expect(output_buffer.to_str).not_to have_tag("form li#post_author_input.string")
end
it "should have author as radio" do
expect(output_buffer.to_str).to have_tag("form li#post_author_input.radio")
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/search_input_spec.rb | spec/inputs/search_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'search input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:search))
end)
end
it_should_have_input_wrapper_with_class(:search)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_search_input")
it_should_have_label_with_text(/Search/)
it_should_have_label_for("post_search")
it_should_have_input_with_id("post_search")
it_should_have_input_with_type(:search)
it_should_have_input_with_name("post[search]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:search))
end)
end
it_should_have_input_wrapper_with_id("context2_post_search_input")
it_should_have_label_and_input_with_id("context2_post_search")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :search))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :search, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/range_input_spec.rb | spec/inputs/range_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'range input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "when object is provided" do
before do
concat(semantic_form_for(@bob) do |builder|
concat(builder.input(:age, :as => :range))
end)
end
it_should_have_input_wrapper_with_class(:range)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:numeric)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("author_age_input")
it_should_have_label_with_text(/Age/)
it_should_have_label_for("author_age")
it_should_have_input_with_id("author_age")
it_should_have_input_with_type(:range)
it_should_have_input_with_name("author[age]")
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@james, :namespace => "context2") do |builder|
concat(builder.input(:age, :as => :range))
end)
end
it_should_have_input_wrapper_with_id("context2_author_age_input")
it_should_have_label_and_input_with_id("context2_author_age")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :range))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
describe "when validations require a minimum value (:greater_than)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than=>2})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min through :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a min attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@min="3"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMinimumAttributeError)
end
end
end
describe "when validations require a minimum value (:greater_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than_or_equal_to=>2})
])
end
it "should allow :input_html to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :min => 5 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :min => 5)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow :input_html to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :in => 5..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
it "should allow options to override :min with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :in => 5..102)
end)
expect(output_buffer.to_str).to have_tag('input[@min="5"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
end
describe "when validations do not require a minimum value" do
it "should default to 1" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@min="1"]')
end
end
describe "when validations require a maximum value (:less_than)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than=>20})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow option to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
describe "and the column is an integer" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :integer))
end
it "should add a max attribute to the input one greater than the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@max="19"]')
end
end
describe "and the column is a float" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :float))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
describe "and the column is a big decimal" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => :decimal))
end
it "should raise an error" do
expect {
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
}.to raise_error(Formtastic::Inputs::Base::Validations::IndeterminableMaximumAttributeError)
end
end
end
describe "when validations require a maximum value (:less_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than_or_equal_to=>20})
])
end
it "should allow :input_html to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :max => 102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :max => 102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow :input_html to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :in => 1..102 })
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
it "should allow options to override :max with :in" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :in => 1..102)
end)
expect(output_buffer.to_str).to have_tag('input[@max="102"]')
end
[:integer, :decimal, :float].each do |column_type|
describe "and the column is a #{column_type}" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(double('column', :type => column_type))
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "and there is no column" do
before do
allow(@new_post).to receive(:column_for_attribute).with(:title).and_return(nil)
end
it "should add a max attribute to the input equal to the validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@max="20"]')
end
end
end
describe "when validations do not require a maximum value" do
it "should default to 1" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@max="100"]')
end
end
describe "when validations require conflicting minimum values (:greater_than, :greater_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :greater_than => 20, :greater_than_or_equal_to=>2})
])
end
it "should add a max attribute to the input equal to the :greater_than_or_equal_to validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@min="2"]')
end
end
describe "when validations require conflicting maximum values (:less_than, :less_than_or_equal_to)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:only_integer=>false, :allow_nil=>false, :less_than => 20, :less_than_or_equal_to=>2})
])
end
it "should add a max attribute to the input equal to the :greater_than_or_equal_to validation" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@max="2"]')
end
end
describe "when validations require only an integer (:only_integer)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false, :only_integer=>true})
])
end
it "should add a step=1 attribute to the input to signify that only whole numbers are allowed" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@step="1"]')
end
it "should let input_html override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
describe "when validations require a :step (non standard)" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false, :only_integer=>true, :step=>2})
])
end
it "should add a step=1 attribute to the input to signify that only whole numbers are allowed" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@step="2"]')
end
it "should let input_html override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options override :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
describe "when validations do not specify :step (non standard) or :only_integer" do
before do
allow(@new_post.class).to receive(:validators_on).with(:title).and_return([
active_model_numericality_validator([:title], {:allow_nil=>false})
])
end
it "should default step to 1" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range)
end)
expect(output_buffer.to_str).to have_tag('input[@step="1"]')
end
it "should let input_html set :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :input_html => { :step => 3 })
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
it "should let options set :step" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :range, :step => 3)
end)
expect(output_buffer.to_str).to have_tag('input[@step="3"]')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/label_spec.rb | spec/inputs/label_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Formtastic::FormBuilder#label' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
it 'should add "required string" only once with caching enabled' do
with_config :i18n_cache_lookups, true do
::I18n.backend.store_translations :en, { :formtastic => { :labels => { :post => { :title => "I18n title" } } } }
required_string = "[req_string]"
default_required_str = Formtastic::FormBuilder.required_string
Formtastic::FormBuilder.required_string = required_string
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :required => true, :label => true)
end)
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :required => true, :label => true)
end)
::I18n.backend.store_translations :en, { :formtastic => { :labels => { :post => { :title => nil } } } }
Formtastic::FormBuilder.required_string = default_required_str
expect(output_buffer.to_s.scan(required_string).count).to eq(1)
end
end
it 'should humanize the given attribute' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title)
end)
expect(output_buffer.to_str).to have_tag('label', :text => /Title/)
end
it 'should apply a "for" attribute to the label' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title)
end)
expect(output_buffer.to_str).to have_tag('label[for=post_title]')
end
it 'should apply a "label" class to the label' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title)
end)
expect(output_buffer.to_str).to have_tag('label.label')
end
it 'should use i18n instead of the method name when method given as a String' do
with_config :i18n_cache_lookups, true do
::I18n.backend.store_translations :en, { :formtastic => { :labels => { :post => { :title => "I18n title" } } } }
concat(semantic_form_for(@new_post) do |builder|
builder.input("title")
end)
::I18n.backend.store_translations :en, { :formtastic => { :labels => { :post => { :title => nil } } } }
expect(output_buffer.to_str).to have_tag('label', :text => /I18n title/)
end
end
it 'should humanize the given attribute for date fields' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:publish_at)
end)
expect(output_buffer.to_str).to have_tag('label', :text => /Publish at/)
end
describe 'when required is given' do
it 'should append a required note' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :required => true)
end)
expect(output_buffer.to_str).to have_tag('label abbr', '*')
end
end
describe "when label_html is given" do
it "should allow label_html to override the class" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label_html => { :class => 'my_class' } )
end)
expect(output_buffer.to_str).to have_tag('label.my_class', /Title/)
end
it "should allow label_html to add custom attributes" do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label_html => { :data => { :tooltip => 'Great Tooltip' } } )
end)
aggregate_failures do
expect(output_buffer.to_str).to have_tag('label[data-tooltip="Great Tooltip"]')
end
end
end
describe 'when a collection is given' do
it 'should use a supplied label_method for simple collections' do
with_deprecation_silenced do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :check_boxes, :collection => [:a, :b, :c], :member_value => :to_s, :member_label => proc {|f| ('Label_%s' % [f])}))
end)
end
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label', :text => /Label_[abc]/, :count => 3)
end
it 'should use a supplied value_method for simple collections' do
with_deprecation_silenced do
concat(semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :check_boxes, :collection => [:a, :b, :c], :member_value => proc {|f| ('Value_%s' % [f.to_s])}))
end)
end
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label input[value="Value_a"]')
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label input[value="Value_b"]')
expect(output_buffer.to_str).to have_tag('form li fieldset ol li label input[value="Value_c"]')
end
end
describe 'when label is given' do
it 'should allow the text to be given as label option' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label => 'My label')
end)
expect(output_buffer.to_str).to have_tag('label', :text => /My label/)
end
it 'should allow the text to be given as label option for date fields' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:publish_at, :label => 'My other label')
end)
expect(output_buffer.to_str).to have_tag('label', :text => /My other label/)
end
it 'should return nil if label is false' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label => false)
end)
expect(output_buffer.to_str).not_to have_tag('label')
expect(output_buffer.to_str).not_to include(">")
end
it 'should return nil if label is false for timeish fragments' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :as => :time_select, :label => false)
end)
expect(output_buffer.to_str).not_to have_tag('li.time > label')
expect(output_buffer.to_str).not_to include(">")
end
it 'should html escape the label string by default' do
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label => '<b>My label</b>')
end)
expect(output_buffer.to_str).to include('<b>')
expect(output_buffer.to_str).not_to include('<b>')
end
it 'should not html escape the label if configured that way' do
Formtastic::FormBuilder.escape_html_entities_in_hints_and_labels = false
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label => '<b>My label</b>')
end)
expect(output_buffer.to_str).to have_tag("label b", :text => "My label")
end
it 'should not html escape the label string for html_safe strings' do
Formtastic::FormBuilder.escape_html_entities_in_hints_and_labels = true
concat(semantic_form_for(@new_post) do |builder|
builder.input(:title, :label => '<b>My label</b>'.html_safe)
end)
expect(output_buffer.to_str).to have_tag('label b')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/file_input_spec.rb | spec/inputs/file_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'file input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:body, :as => :file))
end)
end
it_should_have_input_wrapper_with_class("file")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_body_input")
it_should_have_label_with_text(/Body/)
it_should_have_label_for("post_body")
it_should_have_input_with_id("post_body")
it_should_have_input_with_name("post[body]")
it_should_apply_error_logic_for_input_type(:file)
it 'should use input_html to style inputs' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :file, :input_html => { :class => 'myclass' }))
end)
expect(output_buffer.to_str).to have_tag("form li input.myclass")
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:body, :as => :file))
end)
end
it_should_have_input_wrapper_with_id("context2_post_body_input")
it_should_have_label_and_input_with_id("context2_post_body")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :file))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
context "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :file, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/datetime_picker_input_spec.rb | spec/inputs/datetime_picker_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'datetime_picker input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
after do
::I18n.backend.reload!
end
context "with an object" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_picker))
end)
end
it_should_have_input_wrapper_with_class(:datetime_picker)
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_class(:stringish)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_label_with_text(/Publish at/)
it_should_have_label_for("post_publish_at")
it_should_have_input_with_id("post_publish_at")
it_should_have_input_with_type("datetime-local")
it_should_have_input_with_name("post[publish_at]")
it_should_apply_custom_input_attributes_when_input_html_provided(:datetime_picker)
it_should_apply_custom_for_to_label_when_input_html_id_provided(:datetime_picker)
# TODO why does this blow-up it_should_apply_error_logic_for_input_type(:datetime_picker)
end
describe ":local option for UTC or local time" do
it "should default to a datetime-local input (true)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[type='datetime-local']"
end
it "can be set to true for a datetime-local" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :local => true))
end
)
expect(output_buffer.to_str).to have_tag "input[type='datetime-local']"
end
it "can be set to false for a datetime" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :local => false))
end
)
expect(output_buffer.to_str).to have_tag "input[type='datetime']"
end
end
describe "size attribute" do
it "defaults to 10 chars (YYYY-YY-YY HH:MM)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[size='16']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :size => '12', :input_html => { :size => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[size='12']"
end
end
describe "maxlength attribute" do
it "defaults to 10 chars (YYYY-YY-YY HH:MM)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='16']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='11']"
end
it "can be set from options (ignoring input_html)" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :maxlength => 12, :input_html => { :maxlength => "11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[maxlength='12']"
end
end
describe "value attribute" do
context "when method returns nil" do
it "has no value" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker ))
end
)
expect(output_buffer.to_str).not_to have_tag "li input[value]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :value => "1111-11-11T23:00:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11T23:00:00']"
end
end
context "when method returns a Date" do
before do
@date = Date.new(2000, 11, 11)
allow(@new_post).to receive(:publish_at).and_return(@date)
end
it "renders the date as YYYY-MM-DDT00:00:00" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='2000-11-11T00:00:00']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :value => "1111-11-11T00:00:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11T00:00:00']"
end
end
context "when method returns a Time" do
before do
@time = Time.utc(2000,11,11,11,11,11)
allow(@new_post).to receive(:publish_at).and_return(@time)
end
it "renders the time as a YYYY-MM-DD HH:MM" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='2000-11-11T11:11:11']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :value => "1111-11-11T11:11:11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11T11:11:11']"
end
end
context "when method returns an empty String" do
before do
allow(@new_post).to receive(:publish_at).and_return("")
end
it "will be empty" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :value => "1111-11-11T11:11:11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11T11:11:11']"
end
end
context "when method returns a String" do
before do
allow(@new_post).to receive(:publish_at).and_return("yeah")
end
it "will be the string" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker ))
end
)
expect(output_buffer.to_str).to have_tag "input[value='yeah']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :value => "1111-11-11T11:11:11" }))
end
)
expect(output_buffer.to_str).to have_tag "input[value='1111-11-11T11:11:11']"
end
end
end
describe "min attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[min]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :min => "1970-01-01 12:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[min='1970-01-01 12:00']"
end
end
describe "max attribute" do
it "will be omitted by default" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[max]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :max => "1970-01-01 12:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[max='1970-01-01 12:00']"
end
end
describe "step attribute" do
it "defaults to 1" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).to have_tag "input[step='1']"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :step => "5" }))
end
)
expect(output_buffer.to_str).to have_tag "input[step='5']"
end
describe "macros" do
before do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :step => step }))
end
)
end
context ":second" do
let(:step) { :second }
it "uses 1" do
expect(output_buffer.to_str).to have_tag "input[step='1']"
end
end
context ":minute" do
let(:step) { :minute }
it "uses 60" do
expect(output_buffer.to_str).to have_tag "input[step='60']"
end
end
context ":fifteen_minutes" do
let(:step) { :fifteen_minutes }
it "uses 900" do
expect(output_buffer.to_str).to have_tag "input[step='900']"
end
end
context ":quarter_hour" do
let(:step) { :quarter_hour }
it "uses 900" do
expect(output_buffer.to_str).to have_tag "input[step='900']"
end
end
context ":thirty_minutes" do
let(:step) { :thirty_minutes }
it "uses 1800" do
expect(output_buffer.to_str).to have_tag "input[step='1800']"
end
end
context ":half_hour" do
let(:step) { :half_hour }
it "uses 1800" do
expect(output_buffer.to_str).to have_tag "input[step='1800']"
end
end
context ":hour" do
let(:step) { :hour }
it "uses 3600" do
expect(output_buffer.to_str).to have_tag "input[step='3600']"
end
end
context ":sixty_minutes" do
let(:step) { :sixty_minutes }
it "uses 3600" do
expect(output_buffer.to_str).to have_tag "input[step='3600']"
end
end
end
end
describe "placeholder attribute" do
it "will be omitted" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker))
end
)
expect(output_buffer.to_str).not_to have_tag "input[placeholder]"
end
it "can be set from :input_html options" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:publish_at, :as => :datetime_picker, :input_html => { :placeholder => "1970-01-01 00:00" }))
end
)
expect(output_buffer.to_str).to have_tag "input[placeholder='1970-01-01 00:00']"
end
context "with i18n set" do
before do
::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :publish_at => 'YYYY-MM-DD HH:MM' }}
end
it "can be set with i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_picker))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="YYYY-MM-DD HH:MM"]')
end
end
it "can be set with input_html, trumping i18n" do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_picker, :input_html => { :placeholder => "Something" }))
end)
expect(output_buffer.to_str).to have_tag('input[@placeholder="Something"]')
end
end
end
end
describe "when namespace is provided" do
before do
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:publish_at, :as => :datetime_picker))
end)
end
it_should_have_input_wrapper_with_id("context2_post_publish_at_input")
it_should_have_label_and_input_with_id("context2_post_publish_at")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :datetime_picker))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at]']")
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime_picker, :required => true))
end)
expect(output_buffer.to_str).to have_tag("input[@required]")
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/time_select_input_spec.rb | spec/inputs/time_select_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'time select input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "general" do
before do
::I18n.backend.reload!
@output_buffer = ActionView::OutputBuffer.new ''
end
describe "with :ignore_date => true" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_select, :ignore_date => true))
end)
end
it 'should not have hidden inputs for day, month and year' do
expect(output_buffer.to_str).not_to have_tag('input#post_publish_at_1i')
expect(output_buffer.to_str).not_to have_tag('input#post_publish_at_2i')
expect(output_buffer.to_str).not_to have_tag('input#post_publish_at_3i')
end
it 'should have an input for hour and minute' do
expect(output_buffer.to_str).to have_tag('select#post_publish_at_4i')
expect(output_buffer.to_str).to have_tag('select#post_publish_at_5i')
end
end
describe "with :ignore_date => false" do
before do
allow(@new_post).to receive(:publish_at).and_return(Time.parse('2010-11-07'))
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_select, :ignore_date => false))
end)
end
it 'should have a hidden input for day, month and year' do
expect(output_buffer.to_str).to have_tag('input#post_publish_at_1i')
expect(output_buffer.to_str).to have_tag('input#post_publish_at_2i')
expect(output_buffer.to_str).to have_tag('input#post_publish_at_3i')
expect(output_buffer.to_str).to have_tag('input#post_publish_at_1i[@value="2010"]')
expect(output_buffer.to_str).to have_tag('input#post_publish_at_2i[@value="11"]')
expect(output_buffer.to_str).to have_tag('input#post_publish_at_3i[@value="7"]')
end
it 'should have an select for hour and minute' do
expect(output_buffer.to_str).to have_tag('select#post_publish_at_4i')
expect(output_buffer.to_str).to have_tag('select#post_publish_at_5i')
end
it 'should associate the legend label with the hour select' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset legend.label label[@for="post_publish_at_4i"]')
end
end
describe "without seconds" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_select))
end)
end
it_should_have_input_wrapper_with_class("time_select")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_a_nested_fieldset
it_should_have_a_nested_fieldset_with_class('fragments')
it_should_have_a_nested_ordered_list_with_class('fragments-group')
it_should_apply_error_logic_for_input_type(:time_select)
it 'should have a legend and label with the label text inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset legend.label label', :text => /Publish at/)
end
it 'should associate the legend label with the first select' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset legend.label label[@for="post_publish_at_4i"]')
end
it 'should have an ordered list of two items inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol.fragments-group')
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li.fragment', :count => 2)
end
it 'should have five labels for hour and minute' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :count => 2)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /hour/i)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /minute/i)
end
it 'should have two selects for hour and minute' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li', :count => 2)
end
end
describe "with seconds" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time_select, :include_seconds => true))
end)
end
it 'should have five labels for hour and minute' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :count => 3)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /hour/i)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /minute/i)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /second/i)
end
it 'should have three selects for hour, minute and seconds' do
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li', :count => 3)
end
it 'should generate a sanitized label and matching ids for attribute' do
4.upto(6) do |i|
expect(output_buffer.to_str).to have_tag("form li fieldset ol li label[@for='post_publish_at_#{i}i']")
expect(output_buffer.to_str).to have_tag("form li fieldset ol li #post_publish_at_#{i}i")
end
end
end
end
describe ':labels option' do
fields = [:hour, :minute, :second]
fields.each do |field|
it "should replace the #{field} label with the specified text if :labels[:#{field}] is set" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :time_select, :include_seconds => true, :labels => { field => "another #{field} label" }))
end)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :count => fields.length)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => f == field ? /another #{f} label/i : /#{f}/i)
end
end
it "should not display the label for the #{field} field when :labels[:#{field}] is blank" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :time_select, :include_seconds => true, :labels => { field => "" }))
end)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /#{f}/i) unless field == f
end
end
it "should not render the label when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :time_select, :include_seconds => true, :labels => { field => false }))
end)
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.time_select fieldset ol li label', :text => /#{f}/i) unless field == f
end
end
it "should not render unsafe HTML when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :time_select, :include_seconds => true, :labels => { field => false }))
end)
expect(output_buffer.to_str).not_to include(">")
end
end
it "should not render labels when :labels is falsy" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :time_select, :include_seconds => true, :labels => false))
end)
expect(output_buffer.to_str).not_to have_tag('form li.time_select fieldset ol li label')
end
end
describe ":selected option for setting a value" do
it "should set the selected value for the form" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:created_at, :as => :datetime_select, :selected => DateTime.new(2018, 10, 4, 12, 00)))
end
)
expect(output_buffer.to_str).to have_tag "option[value='12'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='00'][selected='selected']"
end
end
describe ':namespace option' do
before do
concat(semantic_form_for(@new_post, :namespace => 'form2') do |builder|
concat(builder.input(:publish_at, :as => :time_select))
end)
end
it 'should have a tag matching the namespace' do
expect(output_buffer.to_str).to have_tag('#form2_post_publish_at_input')
expect(output_buffer.to_str).to have_tag('#form2_post_publish_at_4i')
expect(output_buffer.to_str).to have_tag('#form2_post_publish_at_5i')
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :time_select, :required => true))
end)
expect(output_buffer.to_str).to have_tag("select[@required]", :count => 2)
end
end
end
describe "when index is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :time_select))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at_1i")
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at_2i")
expect(output_buffer.to_str).to have_tag("input#post_author_attributes_3_created_at_3i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_4i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_5i")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at(1i)]']")
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at(2i)]']")
expect(output_buffer.to_str).to have_tag("input[@name='post[author_attributes][3][created_at(3i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(4i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(5i)]']")
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/datalist_input_spec.rb | spec/inputs/datalist_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe "datalist inputs" do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "renders correctly" do
lists_without_values =[
%w(a b c),
["a", "b", "c"],
("a".."c")
]
lists_with_values = [
{a: 1, b: 2, c:3},
{"a" => 1, "b" => 2, "c" =>3},
[["a",1], ["b",2], ["c", 3]]
]
def self.common_tests(list)
it_should_have_label_with_text(/Document/)
it_should_have_label_for("post_document")
it_should_have_input_wrapper_with_class(:datalist)
it_should_have_input_with(id: "post_document", type: :text, list:"post_document_datalist")
it_should_have_tag_with(:datalist, id: "post_document_datalist" )
it_should_have_many_tags(:option, list.count)
end
context "Rendering list of simple items" do
lists_without_values.each do |list|
describe "renders #{list.to_s} correctly" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:document, as: :datalist, collection: list))
end)
end
common_tests list
it_should_have_tag_with :option, value: list.first
end
end
end
context "Rendering list of complex items, key-value pairs and such" do
lists_with_values.each do |list|
describe "renders #{list.to_s} correctly" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:document, as: :datalist, collection: list))
end)
end
common_tests list
it_should_have_tag_with :option, value: list.first.last
end
end
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/date_select_input_spec.rb | spec/inputs/date_select_input_spec.rb | # encoding: utf-8
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'date select input' do
include FormtasticSpecHelper
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
end
describe "general" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:year, :month, :day]))
end)
end
it_should_have_input_wrapper_with_class("date_select")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_publish_at_input")
it_should_have_a_nested_fieldset
it_should_have_a_nested_fieldset_with_class('fragments')
it_should_have_a_nested_ordered_list_with_class('fragments-group')
it_should_apply_error_logic_for_input_type(:date_select)
it 'should have a legend and label with the label text inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label label', :text => /Publish at/)
end
it 'should associate the legend label with the first select' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label')
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label label')
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label label[@for]')
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label label[@for="post_publish_at_1i"]')
end
it 'should have an ordered list of three items inside the fieldset' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol.fragments-group')
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li.fragment', :count => 3)
end
it 'should have three labels for year, month and day' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :count => 3)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :text => /year/i)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :text => /month/i)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :text => /day/i)
end
it 'should have three selects for year, month and day' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li select', :count => 3)
end
end
describe "when namespace is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post, :namespace => "context2") do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:year, :month, :day]))
end)
end
it_should_have_input_wrapper_with_id("context2_post_publish_at_input")
it_should_have_select_with_id("context2_post_publish_at_1i")
it_should_have_select_with_id("context2_post_publish_at_2i")
it_should_have_select_with_id("context2_post_publish_at_3i")
end
describe "when index is provided" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:created_at, :as => :date_select))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer.to_str).to have_tag("li#post_author_attributes_3_created_at_input")
end
it 'should index the id of the select tag' do
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_1i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_2i")
expect(output_buffer.to_str).to have_tag("select#post_author_attributes_3_created_at_3i")
end
it 'should index the name of the select tag' do
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(1i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(2i)]']")
expect(output_buffer.to_str).to have_tag("select[@name='post[author_attributes][3][created_at(3i)]']")
end
end
describe ':labels option' do
fields = [:year, :month, :day]
fields.each do |field|
it "should replace the #{field} label with the specified text if :labels[:#{field}] is set" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :date_select, :labels => { field => "another #{field} label" }))
end)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :count => fields.length)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :text => f == field ? /another #{f} label/i : /#{f}/i)
end
end
it "should not display the label for the #{field} field when :labels[:#{field}] is blank" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :date_select, :labels => { field => "" }))
end)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :text => /#{f}/i) unless field == f
end
end
it "should not display the label for the #{field} field when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :date_select, :labels => { field => false }))
end)
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', :count => fields.length-1)
fields.each do |f|
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset ol li label', /#{f}/i) unless field == f
end
end
it "should not render unsafe HTML when :labels[:#{field}] is false" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :date_select, :include_seconds => true, :labels => { field => false }))
end)
expect(output_buffer.to_str).not_to include(">")
end
end
it "should not display labels for any fields when :labels is falsy" do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:created_at, :as => :date_select, :labels => false))
end)
expect(output_buffer.to_str).not_to have_tag('form li.date_select fieldset ol li label')
end
end
describe ":selected option for setting a value" do
it "should set the selected value for the form" do
concat(
semantic_form_for(@new_post) do |f|
concat(f.input(:created_at, :as => :datetime_select, :selected => Date.new(2018, 10, 4)))
end
)
expect(output_buffer.to_str).to have_tag "option[value='2018'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='10'][selected='selected']"
expect(output_buffer.to_str).to have_tag "option[value='4'][selected='selected']"
end
end
describe "when required" do
it "should add the required attribute to the input's html options" do
with_config :use_required_attribute, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :date_select, :required => true))
end)
expect(output_buffer.to_str).to have_tag("select[@required]", :count => 3)
end
end
end
describe "when order does not include day" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:year, :month]))
end)
end
it "should include a hidden input for day" do
expect(output_buffer.to_str).to have_tag('input[@type="hidden"][@name="post[publish_at(3i)]"][@value="1"]')
end
it "should not include a select for day" do
expect(output_buffer.to_str).not_to have_tag('select[@name="post[publish_at(3i)]"]')
end
end
describe "when order does not include month" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:year, :day]))
end)
end
it "should include a hidden input for month" do
expect(output_buffer.to_str).to have_tag('input[@type="hidden"][@name="post[publish_at(2i)]"][@value="1"]')
end
it "should not include a select for month" do
expect(output_buffer.to_str).not_to have_tag('select[@name="post[publish_at(2i)]"]')
end
end
describe "when order does not include year" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:month, :day]))
end)
end
it "should include a hidden input for month" do
expect(output_buffer.to_str).to have_tag("input[@type=\"hidden\"][@name=\"post[publish_at(1i)]\"][@value=\"#{Time.now.year}\"]")
end
it "should not include a select for month" do
expect(output_buffer.to_str).not_to have_tag('select[@name="post[publish_at(1i)]"]')
end
end
describe "when order does not have year first" do
before do
@output_buffer = ActionView::OutputBuffer.new ''
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date_select, :order => [:day, :month, :year]))
end)
end
it 'should associate the legend label with the new first select' do
expect(output_buffer.to_str).to have_tag('form li.date_select fieldset legend.label label[@for="post_publish_at_3i"]')
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/base/collections_spec.rb | spec/inputs/base/collections_spec.rb | # frozen_string_literal: true
require 'fast_spec_helper'
require 'inputs/base/collections'
class MyInput
include Formtastic::Inputs::Base::Collections
end
RSpec.describe MyInput do
let(:builder) { double }
let(:template) { double }
let(:model_class) { double }
let(:model) { double(:class => model_class) }
let(:model_name) { "post" }
let(:method) { double }
let(:options) { Hash.new }
let(:instance) { MyInput.new(builder, template, model, model_name, method, options) }
# class Whatever < ActiveRecord::Base
# enum :status => [:active, :archived]
# end
#
# Whatever.statuses
#
# Whatever.new.status
#
# f.input :status
describe "#collection_from_enum" do
let(:method) { :status }
context "when an enum is defined for the method" do
before do
statuses = ActiveSupport::HashWithIndifferentAccess.new("active"=>0, "inactive"=>1)
allow(model_class).to receive(:statuses) { statuses }
allow(model).to receive(:defined_enums) { {"status" => statuses } }
allow(model).to receive(:model_name).and_return(double(i18n_key: model_name))
end
context 'no translations available' do
it 'returns an Array of EnumOption objects based on the enum options hash' do
expect(instance.collection_from_enum).to eq [["Active", "active"],["Inactive", "inactive"]]
end
end
context 'with translations' do
before do
::I18n.backend.store_translations :en, :activerecord => {
:attributes => {
:post => {
:statuses => {
:active => "I am active",
:inactive => "I am inactive"
}
}
}
}
end
it 'returns an Array of EnumOption objects based on the enum options hash' do
expect(instance.collection_from_enum).to eq [["I am active", "active"],["I am inactive", "inactive"]]
end
after do
::I18n.backend.store_translations :en, {}
end
end
end
context "when an enum is not defined" do
it 'returns nil' do
expect(instance.collection_from_enum).to eq nil
end
end
end
describe '#collection' do
context 'when the raw collection is a string' do
it 'returns the string' do
allow(instance).to receive(:raw_collection).and_return("one_status_only")
expect(instance.collection).to eq "one_status_only"
end
end
context 'when the raw collection is an array of strings' do
it 'returns the array of symbols' do
allow(instance).to receive(:raw_collection).and_return(["active", "inactive", "pending"])
expect(instance.collection).to be_an(Array)
expect(instance.collection).to eq ["active", "inactive", "pending"]
end
end
context 'when the raw collection is an array of arrays' do
it 'returns the array of arrays' do
allow(instance).to receive(:raw_collection).and_return([["inactive", "0"], ["active", "1"], ["pending", "2"]])
expect(instance.collection).to be_an(Array)
expect(instance.collection).to eq [["inactive", "0"], ["active", "1"], ["pending", "2"]]
end
end
context 'when the raw collection is an array of symbols' do
it 'returns the array of symbols' do
allow(instance).to receive(:raw_collection).and_return([:active, :inactive, :pending])
expect(instance.collection).to be_an(Array)
expect(instance.collection).to eq [:active, :inactive, :pending]
end
end
context 'when the raw collection is a hash' do
it 'will be mapped into array form' do
allow(instance).to receive(:raw_collection).and_return({ inactive: 0, active: 1, pending: 2 })
expect(instance.collection).to be_an(Array)
expect(instance.collection).to eq [[:inactive, 0], [:active, 1], [:pending, 2]]
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/spec/inputs/base/validations_spec.rb | spec/inputs/base/validations_spec.rb | # frozen_string_literal: true
require 'fast_spec_helper'
require 'active_model'
require 'inputs/base/validations'
class MyInput
attr_accessor :validations
include Formtastic::Inputs::Base::Validations
def validations?
true
end
end
RSpec.describe MyInput do
let(:builder) { double }
let(:template) { double }
let(:model_class) { double }
let(:model) { double(:class => model_class) }
let(:model_name) { "post" }
let(:method) { double }
let(:options) { Hash.new }
let(:validator) { double }
let(:instance) do
MyInput.new(builder, template, model, model_name, method, options).tap do |my_input|
my_input.validations = validations
end
end
describe '#required?' do
context 'with a single validator' do
let(:validations) { [validator] }
context 'with options[:required] being true' do
let(:options) { {required: true} }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with options[:required] being false' do
let(:options) { {required: false} }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'with negated validation' do
it 'is not required' do
instance.not_required_through_negated_validation!
expect(instance.required?).to be_falsey
end
end
context 'with presence validator' do
let (:validator) { double(options: {}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
context 'with options[:on] as symbol' do
context 'with save context' do
let (:validator) { double(options: {on: :save}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with create context' do
let (:validator) { double(options: {on: :create}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update context' do
let (:validator) { double(options: {on: :update}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
end
context 'with options[:on] as array' do
context 'with save context' do
let (:validator) { double(options: {on: [:save]}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with create context' do
let (:validator) { double(options: {on: [:create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update context' do
let (:validator) { double(options: {on: [:update]}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and create context' do
let (:validator) { double(options: {on: [:save, :create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and update context' do
let (:validator) { double(options: {on: [:save, :create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with create and update context' do
let (:validator) { double(options: {on: [:create, :update]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and other context' do
let (:validator) { double(options: {on: [:save, :foo]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with create and other context' do
let (:validator) { double(options: {on: [:create, :foo]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update and other context' do
let (:validator) { double(options: {on: [:update, :foo]}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
end
end
context 'with inclusion validator' do
context 'with allow blank' do
let (:validator) { double(options: {allow_blank: true}, kind: :inclusion) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'without allow blank' do
let (:validator) { double(options: {allow_blank: false}, kind: :inclusion) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
end
context 'with a length validator' do
context 'with allow blank' do
let (:validator) { double(options: {allow_blank: true}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'without allow blank' do
let (:validator) { double(options: {allow_blank: false}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
context 'with a minimum > 0' do
let (:validator) { double(options: {allow_blank: false, minimum: 1}, kind: :length) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a minimum <= 0' do
let (:validator) { double(options: {allow_blank: false, minimum: 0}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'with a defined range starting with > 0' do
let (:validator) { double(options: {allow_blank: false, within: 1..5}, kind: :length) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a defined range starting with <= 0' do
let (:validator) { double(options: {allow_blank: false, within: 0..5}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
end
end
context 'with another validator' do
let (:validator) { double(options: {allow_blank: true}, kind: :foo) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
end
context 'with multiple validators' do
let(:validations) { [validator1, validator2] }
context 'with a on create presence validator and a on update presence validator' do
let(:validator1) { double(options: {on: :create}, kind: :presence) }
let(:validator2) { double(options: {}, kind: :presence) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
end
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a on create presence validator and a presence validator' do
let (:validator1) { double(options: {on: :create}, kind: :presence) }
let (:validator2) { double(options: {}, kind: :presence) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
end
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a on create presence validator and a allow blank inclusion validator' do
let(:validator1) { double(options: {on: :create}, kind: :presence) }
let(:validator2) { double(options: {allow_blank: true}, kind: :inclusion) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
end
it 'is required' do
expect(instance.required?).to be_falsey
end
end
end
end
describe '#validation_min' do
let(:validations) { [validator] }
context 'with a greater_than numericality validator' do
let(:validator) { double(options: { greater_than: option_value }, kind: :numericality) }
context 'with a symbol' do
let(:option_value) { :a_symbol }
it 'returns one greater' do
allow(model).to receive(:send).with(option_value).and_return(14)
expect(instance.validation_min).to eq 15
end
end
context 'with a proc' do
let(:option_value) { Proc.new { 10 } }
it 'returns one greater' do
expect(instance.validation_min).to eq 11
end
end
context 'with a number' do
let(:option_value) { 8 }
it 'returns one greater' do
expect(instance.validation_min).to eq 9
end
end
end
context 'with a greater_than_or_equal_to numericality validator' do
let(:validator) do
double(
options: { greater_than_or_equal_to: option_value },
kind: :numericality
)
end
context 'with a symbol' do
let(:option_value) { :a_symbol }
it 'returns the instance method amount' do
allow(model).to receive(:send).with(option_value).and_return(14)
expect(instance.validation_min).to eq 14
end
end
context 'with a proc' do
let(:option_value) { Proc.new { 10 } }
it 'returns the proc amount' do
expect(instance.validation_min).to eq 10
end
end
context 'with a number' do
let(:option_value) { 8 }
it 'returns the number' do
expect(instance.validation_min).to eq 8
end
end
end
end
describe '#validation_max' do
let(:validations) do
[
ActiveModel::Validations::NumericalityValidator.new(
validator_options.merge(attributes: :an_attribute)
)
]
end
context 'with a less_than numericality validator' do
let(:validator_options) { { less_than: option_value } }
context 'with a symbol' do
let(:option_value) { :a_symbol }
it 'returns one less' do
allow(model).to receive(:send).with(option_value).and_return(14)
expect(instance.validation_max).to eq 13
end
end
context 'with a proc' do
let(:option_value) { proc { 10 } }
it 'returns one less' do
expect(instance.validation_max).to eq 9
end
end
context 'with a number' do
let(:option_value) { 8 }
it 'returns one less' do
expect(instance.validation_max).to eq 7
end
end
end
context 'with a less_than_or_equal_to numericality validator' do
let(:validator_options) { { less_than_or_equal_to: option_value } }
context 'with a symbol' do
let(:option_value) { :a_symbol }
it 'returns the instance method amount' do
allow(model).to receive(:send).with(option_value).and_return(14)
expect(instance.validation_max).to eq 14
end
end
context 'with a proc' do
let(:option_value) { proc { 10 } }
it 'returns the proc amount' do
expect(instance.validation_max).to eq 10
end
end
context 'with a number' do
let(:option_value) { 8 }
it 'returns the number' do
expect(instance.validation_max).to eq 8
end
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/script/integration-template.rb | script/integration-template.rb | # frozen_string_literal: true
gem 'formtastic', path: '..'
gem 'bcrypt', '~> 3.1.7'
gem 'rails-dom-testing', group: :test
gem 'rexml', '~> 3.2' # to compensate for missing dependency in selenium-webdriver
# to speed up bundle install, reuse the bundle path
def bundle_path
File.expand_path ENV.fetch('BUNDLE_PATH', 'vendor/bundle')
end
if Rails.version >= '6.2'
gsub_file 'Gemfile', /gem 'rails'.*/, "gem 'rails', '~> #{Rails.version}', github: 'rails/rails'"
elsif Rails.version >= '6.1'
gsub_file 'Gemfile', /gem 'rails'.*/, "gem 'rails', '~> #{Rails.version}', github: 'rails/rails', branch: '6-1-stable'"
elsif Rails.version >= '6.0'
gsub_file 'Gemfile', /gem 'rails'.*/, "gem 'rails', '~> #{Rails.version}', github: 'rails/rails', branch: '6-0-stable'"
end
### Ensure Dummy App's Ruby version matches the current environments Ruby Version
ruby_version = "ruby '#{RUBY_VERSION}'"
gsub_file 'Gemfile', /ruby '\d+.\d+.\d+'/, ruby_version
if bundle_install?
def run_bundle
previous_bundle_path = bundle_path
require "bundler"
Bundler.with_clean_env do
system("bundle install --jobs=3 --retry=3 --path=#{previous_bundle_path}")
end
end
end
in_root do
ENV['BUNDLE_GEMFILE'] = File.expand_path('Gemfile')
end
formtastic = -> do
generate(:scaffold, 'user name:string password:digest')
generate('formtastic:install')
generate('formtastic:form', 'user name password --force')
rails_command('db:migrate')
in_root do
inject_into_class 'app/models/user.rb', 'User', " has_secure_password\n"
inject_into_file 'app/assets/stylesheets/application.css', " *= require formtastic\n", before: ' *= require_self'
inject_into_class 'test/controllers/users_controller_test.rb', 'UsersControllerTest', <<-RUBY
test "should show form" do
get edit_user_path(@user)
assert_select 'form' do
assert_select 'li.input.string' do
assert_select 'input#user_name[type=text]'
end
assert_select 'li.input.password' do
assert_select 'input#user_password[type=password]'
end
assert_select 'fieldset.actions' do
assert_select 'li.action.input_action' do
assert_select 'input[type=submit]'
end
end
end
end # test "should show form"
RUBY
end
end
after_bundle(&formtastic)
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/formtastic.rb | lib/formtastic.rb | # encoding: utf-8
# frozen_string_literal: true
module Formtastic
extend ActiveSupport::Autoload
autoload :Helpers
autoload :HtmlAttributes
autoload :LocalizedString
autoload :Localizer
autoload :NamespacedClassFinder
autoload :InputClassFinder
autoload :ActionClassFinder
autoload :Deprecation
eager_autoload do
autoload :I18n
autoload :FormBuilder
autoload :Inputs
autoload :Actions
end
# @public
class UnknownInputError < NameError
end
# @private
class UnknownActionError < NameError
end
# @private
class PolymorphicInputWithoutCollectionError < ArgumentError
end
# @private
class UnsupportedMethodForAction < ArgumentError
end
# @private
class UnsupportedEnumCollection < NameError
end
end
if defined?(::Rails)
ActiveSupport.on_load(:action_view) do
include Formtastic::Helpers::FormHelper
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/formtastic/stylesheets/stylesheets_generator.rb | lib/generators/formtastic/stylesheets/stylesheets_generator.rb | module Formtastic
# Copies a stylesheet into to app/assets/stylesheets/formtastic.css
#
# @example
# !!!shell
# $ rails generate formtastic:stylesheets
class StylesheetsGenerator < Rails::Generators::Base
source_root File.expand_path("../../../templates", __FILE__)
desc "Copies Formtastic example stylesheet into your app"
def copy_files
puts "hey"
copy_file "formtastic.css", "app/assets/stylesheets/formtastic.css"
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/formtastic/input/input_generator.rb | lib/generators/formtastic/input/input_generator.rb | # frozen_string_literal: true
module Formtastic
# Modify existing inputs, subclass them, or create your own from scratch.
# @example
# !!!shell
# $ rails generate formtastic:input HatSize
# @example Define input name using underscore convention
# !!!shell
# $ rails generate formtastic:input hat_size
# @example Override an existing input behavior
# !!!shell
# $ rails generate formtastic:input string --extend
# @example Extend an existing input behavior
# !!!shell
# $ rails generate formtastic:input FlexibleText --extend string
class InputGenerator < Rails::Generators::NamedBase
argument :name, :type => :string, :required => true, :banner => 'FILE_NAME'
source_root File.expand_path('../../../templates', __FILE__)
class_option :extend
def create
normalize_file_name
define_extension_sentence
template "input.rb", "app/inputs/#{name.underscore}_input.rb"
end
protected
def normalize_file_name
name.chomp!("Input") if name.ends_with?("Input")
name.chomp!("_input") if name.ends_with?("_input")
name.chomp!("input") if name.ends_with?("input")
end
def define_extension_sentence
@extension_sentence = "< Formtastic::Inputs::#{name.camelize}Input" if options[:extend] == "extend"
@extension_sentence ||= "< Formtastic::Inputs::#{options[:extend].camelize}Input" if options[:extend]
end
end
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/formtastic/form/form_generator.rb | lib/generators/formtastic/form/form_generator.rb | # encoding: utf-8
# frozen_string_literal: true
module Formtastic
# Generates a Formtastic form partial based on an existing model. It will not overwrite existing
# files without confirmation.
#
# @example
# !!!shell
# $ rails generate formtastic:form Post
# @example Copy the partial code to the pasteboard rather than generating a partial
# !!!shell
# $ rails generate formtastic:form Post --copy
# @example Return HAML or Slim output instead of default ERB
# !!!shell
# $ rails generate formtastic:form Post --template-engine haml
# $ rails generate formtastic:form Post --template-engine slim
# @example Generate a form for specific model attributes
# !!!shell
# $ rails generate formtastic:form Post title:string body:text
# @example Generate a form for a specific controller
# !!!shell
# $ rails generate formtastic:form Post --controller admin/posts
class FormGenerator < Rails::Generators::NamedBase
desc "Generates a Formtastic form partial based on an existing model."
argument :name, :type => :string, :required => true, :banner => 'MODEL_NAME'
argument :attributes, :type => :array, :default => [], :banner => 'attribute attribute'
source_root File.expand_path('../../../templates', __FILE__)
class_option :template_engine
class_option :copy, :type => :boolean, :default => false, :group => :formtastic,
:desc => 'Copy the generated code the clipboard instead of generating a partial file."'
class_option :controller, :type => :string, :default => nil, :group => :formtastic,
:desc => 'Generate for custom controller/view path - in case model and controller namespace is different, i.e. "admin/posts"'
def create_or_show
@attributes = reflected_attributes if @attributes.empty?
engine = options[:template_engine]
if options[:copy]
template = File.read("#{self.class.source_root}/_form.html.#{engine}")
erb = ERB.new(template, trim_mode: '-')
generated_code = erb.result(binding).strip rescue nil
puts "The following code has been copied to the clipboard, just paste it in your views:" if save_to_clipboard(generated_code)
puts generated_code || "Error: Nothing generated. Does the model exist?"
else
empty_directory "app/views/#{controller_path}"
template "_form.html.#{engine}", "app/views/#{controller_path}/_form.html.#{engine}"
end
end
protected
def controller_path
@controller_path ||= if options[:controller]
options[:controller].underscore
else
name.underscore.pluralize
end
end
def reflected_attributes
columns = content_columns
columns += association_columns
end
def model
@model ||= name.camelize.constantize
end
# Collects content columns (non-relation columns) for the current class.
# Skips Active Record Timestamps.
def content_columns
model.content_columns.select do |column|
!Formtastic::FormBuilder.skipped_columns.include? column.name.to_sym
end
end
# Collects association columns (relation columns) for the current class. Skips polymorphic
# associations because we can't guess which class to use for an automatically generated input.
def association_columns
model.reflect_on_all_associations(:belongs_to).select do |association_reflection|
association_reflection.options[:polymorphic] != true
end
end
def save_to_clipboard(data)
return unless data
begin
case RUBY_PLATFORM
when /win32/
require 'win32/clipboard'
::Win32::Clipboard.data = data
when /darwin/ # mac
`echo "#{data}" | pbcopy`
else # linux/unix
`echo "#{data}" | xsel --clipboard` || `echo "#{data}" | xclip`
end
rescue LoadError
false
else
true
end
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/formtastic/install/install_generator.rb | lib/generators/formtastic/install/install_generator.rb | # encoding: utf-8
# frozen_string_literal: true
module Formtastic
# Copies a config initializer to config/initializers/formtastic.rb
#
# @example
# !!!shell
# $ rails generate formtastic:install
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../../../templates', __FILE__)
class_option :template_engine
desc "Copies a config initializer to config/initializers/formtastic.rb"
def copy_files
copy_file 'formtastic.rb', 'config/initializers/formtastic.rb'
end
def copy_scaffold_template
engine = options[:template_engine]
copy_file "_form.html.#{engine}", "lib/templates/#{engine}/scaffold/_form.html.#{engine}"
end
end
end
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/templates/input.rb | lib/generators/templates/input.rb | class <%= name.camelize %>Input <%= @extension_sentence %>
<%- if !options[:extend] -%>
include Formtastic::Inputs::Base
<%- end -%>
<%- if !options[:extend] || (options[:extend] == "extend") -%>
def to_html
# Add your custom input definition here.
<%- if options[:extend] == "extend" -%>
super
<%- end -%>
end
<%- else -%>
def input_html_options
# Add your custom input extension here.
end
<%- end -%>
end | ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
formtastic/formtastic | https://github.com/formtastic/formtastic/blob/3ed00c52ab2472a02fe1f63a4327fde401c7472e/lib/generators/templates/formtastic.rb | lib/generators/templates/formtastic.rb | # encoding: utf-8
# frozen_string_literal: true
# Set the default text field size when input is a string. Default is nil.
# Formtastic::FormBuilder.default_text_field_size = 50
# Set the default text area height when input is a text. Default is 20.
# Formtastic::FormBuilder.default_text_area_height = 5
# Set the default text area width when input is a text. Default is nil.
# Formtastic::FormBuilder.default_text_area_width = 50
# Should all fields be considered "required" by default?
# Defaults to true.
# Formtastic::FormBuilder.all_fields_required_by_default = true
# Should select fields have a blank option/prompt by default?
# Defaults to true.
# Formtastic::FormBuilder.include_blank_for_select_by_default = true
# Set the string that will be appended to the labels/fieldsets which are required.
# It accepts string or procs and the default is a localized version of
# '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required
# in your locale, it will replace the abbr title properly. But if you don't want to use
# abbr tag, you can simply give a string as below.
# Formtastic::FormBuilder.required_string = "(required)"
# Set the string that will be appended to the labels/fieldsets which are optional.
# Defaults to an empty string ("") and also accepts procs (see required_string above).
# Formtastic::FormBuilder.optional_string = "(optional)"
# Set the way inline errors will be displayed.
# Defaults to :sentence, valid options are :sentence, :list, :first and :none
# Formtastic::FormBuilder.inline_errors = :sentence
# Formtastic uses the following classes as default for hints, inline_errors and error list
# If you override the class here, please ensure to override it in your stylesheets as well.
# Formtastic::FormBuilder.default_hint_class = "inline-hints"
# Formtastic::FormBuilder.default_inline_error_class = "inline-errors"
# Formtastic::FormBuilder.default_error_list_class = "errors"
# Set the method to call on label text to transform or format it for human-friendly
# reading when formtastic is used without object. Defaults to :humanize.
# Formtastic::FormBuilder.label_str_method = :humanize
# Set the array of methods to try calling on parent objects in :select and :radio inputs
# for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method
# that is found on the object will be used.
# Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
# Formtastic::FormBuilder.collection_label_methods = [
# "to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
# Specifies if labels/hints for input fields automatically be looked up using I18n.
# Default value: true. Overridden for specific fields by setting value to true,
# i.e. :label => true, or :hint => true (or opposite depending on initialized value)
# Formtastic::FormBuilder.i18n_lookups_by_default = false
# Specifies if I18n lookups of the default I18n Localizer should be cached to improve performance.
# Defaults to true.
# Formtastic::FormBuilder.i18n_cache_lookups = false
# Specifies the class to use for localization lookups. You can create your own
# class and use it instead by subclassing Formtastic::Localizer (which is the default).
# Formtastic::FormBuilder.i18n_localizer = MyOwnLocalizer
# You can add custom inputs or override parts of Formtastic by subclassing Formtastic::FormBuilder and
# specifying that class here. Defaults to Formtastic::FormBuilder.
# Formtastic::Helpers::FormHelper.builder = MyCustomBuilder
# All formtastic forms have a class that indicates that they are just that. You
# can change it to any class you want.
# Formtastic::Helpers::FormHelper.default_form_class = 'formtastic'
# Formtastic will infer a class name from the model, array, string or symbol you pass to the
# form builder. You can customize the way that class is presented by overriding
# this proc.
# Formtastic::Helpers::FormHelper.default_form_model_class_proc = proc { |model_class_name| model_class_name }
# Allows to set a custom field_error_proc wrapper. By default this wrapper
# is disabled since `formtastic` already adds an error class to the LI tag
# containing the input.
# Formtastic::Helpers::FormHelper.formtastic_field_error_proc = proc { |html_tag, instance_tag| html_tag }
# You can opt-in to Formtastic's use of the HTML5 `required` attribute on `<input>`, `<select>`
# and `<textarea>` tags by setting this to true (defaults to false).
# Formtastic::FormBuilder.use_required_attribute = false
# You can opt-in to new HTML5 browser validations (for things like email and url inputs) by setting
# this to true. Doing so will omit the `novalidate` attribute from the `<form>` tag.
# See http://diveintohtml5.org/forms.html#validation for more info.
# Formtastic::FormBuilder.perform_browser_validations = true
# By creating custom input class finder, you can change how input classes are looked up.
# For example you can make it to search for TextInputFilter instead of TextInput.
# See https://github.com/formtastic/formtastic/wiki/Custom-Class-Finders
# Formtastic::FormBuilder.input_class_finder = Formtastic::InputClassFinder
# Define custom namespaces in which to look up your Input classes. Default is
# to look up in the global scope and in Formtastic::Inputs.
# Formtastic::FormBuilder.input_namespaces = [ ::Object, ::MyInputsModule, ::Formtastic::Inputs ]
# By creating custom action class finder, you can change how action classes are looked up.
# For example you can make it to search for MyButtonAction instead of ButtonAction.
# See https://github.com/formtastic/formtastic/wiki/Custom-Class-Finders
# Formtastic::FormBuilder.action_class_finder = Formtastic::ActionClassFinder
# Define custom namespaces in which to look up your Action classes. Default is
# to look up in the global scope and in Formtastic::Actions.
# Formtastic::FormBuilder.action_namespaces = [ ::Object, ::MyActionsModule, ::Formtastic::Actions ]
# Which columns to skip when automatically rendering a form without any fields specified.
# Formtastic::FormBuilder.skipped_columns = [:created_at, :updated_at, :created_on, :updated_on, :lock_version, :version]
# You can opt-in to accessibility features for the `semantic_errors` helper by setting
# this to true. Doing so will render the attributes in the error summary list
# as `<li> <a>` links to the inputs that have errors. the inline error sentence's id is added to
# the errored input's aria-describedby. This ensures that the errored input is read out with
# the inline error sentence's error explanation, aria-invalid is set to true for errored inputs
# Formtastic::FormBuilder.semantic_errors_link_to_inputs = true
| ruby | MIT | 3ed00c52ab2472a02fe1f63a4327fde401c7472e | 2026-01-04T15:43:36.501686Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.