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 |
|---|---|---|---|---|---|---|---|---|
flyerhzm/bullet | https://github.com/flyerhzm/bullet/blob/5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0/lib/bullet/registry/call_stack.rb | lib/bullet/registry/call_stack.rb | # frozen_string_literal: true
module Bullet
module Registry
class CallStack < Base
# remembers found association backtrace
def add(key)
@registry[key] ||= Thread.current.backtrace
end
end
end
end
| ruby | MIT | 5f4173292a0566ca5ba0b1ff8e1d6362f3be85b0 | 2026-01-04T15:39:36.933591Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth_spec.rb | spec/omniauth_spec.rb | require 'helper'
describe OmniAuth do
describe '.strategies' do
it 'increases when a new strategy is made' do
expect do
class ExampleStrategy
include OmniAuth::Strategy
end
end.to change(OmniAuth.strategies, :size).by(1)
expect(OmniAuth.strategies.last).to eq(ExampleStrategy)
end
end
context 'configuration' do
describe '.defaults' do
it 'is a hash of default configuration' do
expect(OmniAuth::Configuration.defaults).to be_kind_of(Hash)
end
end
it 'is callable from .configure' do
OmniAuth.configure do |c|
expect(c).to be_kind_of(OmniAuth::Configuration)
end
end
before do
@old_path_prefix = OmniAuth.config.path_prefix
@old_on_failure = OmniAuth.config.on_failure
@old_before_callback_phase = OmniAuth.config.before_callback_phase
@old_before_options_phase = OmniAuth.config.before_options_phase
@old_before_request_phase = OmniAuth.config.before_request_phase
@old_after_request_phase = OmniAuth.config.after_request_phase
@old_request_validation_phase = OmniAuth.config.request_validation_phase
end
after do
OmniAuth.configure do |config|
config.path_prefix = @old_path_prefix
config.on_failure = @old_on_failure
config.before_callback_phase = @old_before_callback_phase
config.before_options_phase = @old_before_options_phase
config.before_request_phase = @old_before_request_phase
config.after_request_phase = @old_after_request_phase
config.request_validation_phase = @old_request_validation_phase
end
end
it 'is able to set the path' do
OmniAuth.configure do |config|
config.path_prefix = '/awesome'
end
expect(OmniAuth.config.path_prefix).to eq('/awesome')
end
it 'is able to set the on_failure rack app' do
OmniAuth.configure do |config|
config.on_failure do
'yoyo'
end
end
expect(OmniAuth.config.on_failure.call).to eq('yoyo')
end
it 'is able to set hook on option_call' do
OmniAuth.configure do |config|
config.before_options_phase do
'yoyo'
end
end
expect(OmniAuth.config.before_options_phase.call).to eq('yoyo')
end
it 'is able to set hook on request_call' do
OmniAuth.configure do |config|
config.before_request_phase do
'heyhey'
end
end
expect(OmniAuth.config.before_request_phase.call).to eq('heyhey')
end
it 'is able to set hook on callback_call' do
OmniAuth.configure do |config|
config.before_callback_phase do
'heyhey'
end
end
expect(OmniAuth.config.before_callback_phase.call).to eq('heyhey')
end
it 'is able to set request_validation_phase' do
OmniAuth.configure do |config|
config.request_validation_phase do
'validated'
end
end
expect(OmniAuth.config.request_validation_phase.call).to eq('validated')
end
describe 'mock auth' do
before do
@auth_hash = {:uid => '12345', :info => {:name => 'Joe', :email => 'joe@example.com'}}
@original_auth_hash = @auth_hash.dup
OmniAuth.config.add_mock(:facebook, @auth_hash)
end
it 'default is AuthHash' do
OmniAuth.configure do |config|
expect(config.mock_auth[:default]).to be_kind_of(OmniAuth::AuthHash)
end
end
it 'facebook is AuthHash' do
OmniAuth.configure do |config|
expect(config.mock_auth[:facebook]).to be_kind_of(OmniAuth::AuthHash)
end
end
it 'sets facebook attributes' do
OmniAuth.configure do |config|
expect(config.mock_auth[:facebook].uid).to eq('12345')
expect(config.mock_auth[:facebook].info.name).to eq('Joe')
expect(config.mock_auth[:facebook].info.email).to eq('joe@example.com')
end
end
it 'does not mutate given auth hash' do
OmniAuth.configure do
expect(@auth_hash).to eq @original_auth_hash
end
end
end
end
describe '.logger' do
it 'calls through to the configured logger' do
allow(OmniAuth).to receive(:config).and_return(double(:logger => 'foo'))
expect(OmniAuth.logger).to eq('foo')
end
end
describe '::Utils' do
describe 'form_css' do
it 'returns a style tag with the configured form_css' do
allow(OmniAuth).to receive(:config).and_return(double(:form_css => 'css.css'))
expect(OmniAuth::Utils.form_css).to eq "<style type='text/css'>css.css</style>"
end
end
describe '.deep_merge' do
it 'combines hashes' do
expect(OmniAuth::Utils.deep_merge({'abc' => {'def' => 123}}, 'abc' => {'foo' => 'bar'})).to eq('abc' => {'def' => 123, 'foo' => 'bar'})
end
end
describe '.camelize' do
it 'works on normal cases' do
{
'some_word' => 'SomeWord',
'AnotherWord' => 'AnotherWord',
'one' => 'One',
'three_words_now' => 'ThreeWordsNow'
}.each_pair { |k, v| expect(OmniAuth::Utils.camelize(k)).to eq(v) }
end
it 'works in special cases that have been added' do
OmniAuth.config.add_camelization('oauth', 'OAuth')
expect(OmniAuth::Utils.camelize(:oauth)).to eq('OAuth')
end
it 'doesn\'t uppercase the first letter when passed false' do
expect(OmniAuth::Utils.camelize('apple_jack', false)).to eq('appleJack')
end
it 'replaces / with ::' do
expect(OmniAuth::Utils.camelize('apple_jack/cereal')).to eq('AppleJack::Cereal')
expect(OmniAuth::Utils.camelize('apple_jack/cereal', false)).to eq('appleJack::Cereal')
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/helper.rb | spec/helper.rb | require 'simplecov'
require 'coveralls'
require 'simplecov-lcov'
SimpleCov::Formatter::LcovFormatter.config.report_with_single_file = true
SimpleCov.formatters = [
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::LcovFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start do
add_filter ['/spec/', '/vendor/', 'strategy_macros.rb']
minimum_coverage(92.5)
maximum_coverage_drop(0.05)
end
require 'rspec'
require 'rack/test'
require 'rack/freeze'
require 'omniauth'
require 'omniauth/test'
OmniAuth.config.logger = Logger.new('/dev/null')
OmniAuth.config.request_validation_phase = nil
RSpec.configure do |config|
config.include Rack::Test::Methods
config.extend OmniAuth::Test::StrategyMacros, :type => :strategy
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
class ExampleStrategy
include OmniAuth::Strategy
attr_reader :last_env
option :name, 'test'
def call(env)
options[:dup] ? super : call!(env)
end
def initialize(*args, &block)
super
@fail = nil
end
def request_phase
options[:mutate_on_request].call(options) if options[:mutate_on_request]
@fail = fail!(options[:failure], options[:failure_exception]) if options[:failure]
@last_env = env
return @fail if @fail
raise('Request Phase')
end
def callback_phase
options[:mutate_on_callback].call(options) if options[:mutate_on_callback]
@fail = fail!(options[:failure], options[:failure_exception]) if options[:failure]
@last_env = env
return @fail if @fail
raise('Callback Phase')
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/form_spec.rb | spec/omniauth/form_spec.rb | require 'helper'
describe OmniAuth::Form do
describe '.build' do
it 'yields the instance when called with a block and argument' do
OmniAuth::Form.build { |f| expect(f).to be_kind_of(OmniAuth::Form) }
end
it 'evaluates in the instance when called with a block and no argument' do
f = OmniAuth::Form.build { @html = '<h1>OmniAuth</h1>' }
expect(f.instance_variable_get(:@html)).to eq('<h1>OmniAuth</h1>')
end
end
describe '#initialize' do
it 'sets the form action to the passed :url option' do
expect(OmniAuth::Form.new(:url => '/awesome').to_html).to be_include("action='/awesome'")
end
it 'sets an H1 tag from the passed :title option' do
expect(OmniAuth::Form.new(:title => 'Something Cool').to_html).to be_include('<h1>Something Cool</h1>')
end
it 'sets the default form method to post' do
expect(OmniAuth::Form.new.to_html).to be_include("method='post'")
end
it 'sets the form method to the passed :method option' do
expect(OmniAuth::Form.new(:method => 'get').to_html).to be_include("method='get'")
end
end
describe '#password_field' do
it 'adds a labeled input field' do
form = OmniAuth::Form.new.password_field('pass', 'password')
form_html = form.to_html
expect(form_html).to include('<label for=\'password\'>pass:</label>')
expect(form_html).to include('<input type=\'password\' id=\'password\' name=\'password\'/>')
end
end
describe '#html' do
it 'appends to the html body' do
form = OmniAuth::Form.build { @html = +'<p></p>' }
form.html('<h1></h1>')
expect(form.instance_variable_get(:@html)).to eq '<p></p><h1></h1>'
end
end
describe 'fieldset' do
it 'creates a fieldset with options' do
form = OmniAuth::Form.new
options = {:style => 'color: red', :id => 'fieldSetId'}
expected = "<fieldset style='color: red' id='fieldSetId'>\n <legend>legendary</legend>\n\n</fieldset>"
form.fieldset('legendary', options) {}
expect(form.to_html).to include expected
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/strategy_spec.rb | spec/omniauth/strategy_spec.rb | require 'helper'
def make_env(path = '/auth/test', props = {})
{
'REQUEST_METHOD' => 'POST',
'PATH_INFO' => path,
'rack.session' => {},
'rack.input' => StringIO.new('test=true')
}.merge(props)
end
describe OmniAuth::Strategy do
let(:app) do
lambda { |_env| [404, {}, ['Awesome']] }
end
let(:fresh_strategy) do
c = Class.new
c.send(:include, OmniAuth::Strategy)
end
describe '.default_options' do
it 'is inherited from a parent class' do
superklass = Class.new
superklass.send :include, OmniAuth::Strategy
superklass.configure do |c|
c.foo = 'bar'
end
klass = Class.new(superklass)
expect(klass.default_options.foo).to eq('bar')
end
end
describe 'user_info' do
it 'should default to an empty hash' do
expect(fresh_strategy.new(app, :skip_info => true).user_info).to eq({})
end
end
describe '.configure' do
subject do
c = Class.new
c.send(:include, OmniAuth::Strategy)
end
context 'when block is passed' do
it 'allows for default options setting' do
subject.configure do |c|
c.wakka = 'doo'
end
expect(subject.default_options['wakka']).to eq('doo')
end
it "works when block doesn't evaluate to true" do
environment_variable = nil
subject.configure do |c|
c.abc = '123'
c.hgi = environment_variable
end
expect(subject.default_options['abc']).to eq('123')
end
end
it 'takes a hash and deep merge it' do
subject.configure :abc => {:def => 123}
subject.configure :abc => {:hgi => 456}
expect(subject.default_options['abc']).to eq('def' => 123, 'hgi' => 456)
end
end
describe '#fail!' do
it 'provides exception information when one is provided' do
env = make_env
exception = RuntimeError.new('No session!')
expect(OmniAuth.logger).to receive(:error).with(
"(test) Authentication failure! failed: #{exception.class}, #{exception.message}"
)
ExampleStrategy.new(app, :failure => :failed, :failure_exception => exception).call(env)
end
it 'provides a generic message when not provided an exception' do
env = make_env
expect(OmniAuth.logger).to receive(:error).with(
'(test) Authentication failure! Some Issue encountered.'
)
ExampleStrategy.new(app, :failure => 'Some Issue').call(env)
end
end
describe '#skip_info?' do
it 'is true if options.skip_info is true' do
expect(ExampleStrategy.new(app, :skip_info => true)).to be_skip_info
end
it 'is false if options.skip_info is false' do
expect(ExampleStrategy.new(app, :skip_info => false)).not_to be_skip_info
end
it 'is false by default' do
expect(ExampleStrategy.new(app)).not_to be_skip_info
end
it 'is true if options.skip_info is a callable that evaluates to truthy' do
instance = ExampleStrategy.new(app, :skip_info => lambda { |uid| uid })
expect(instance).to receive(:uid).and_return(true)
expect(instance).to be_skip_info
end
end
describe '.option' do
subject do
c = Class.new
c.send(:include, OmniAuth::Strategy)
end
it 'sets a default value' do
subject.option :abc, 123
expect(subject.default_options.abc).to eq(123)
end
it 'sets the default value to nil if none is provided' do
subject.option :abc
expect(subject.default_options.abc).to be_nil
end
end
describe '.args' do
subject do
c = Class.new
c.send(:include, OmniAuth::Strategy)
end
it 'sets args to the specified argument if there is one' do
subject.args %i[abc def]
expect(subject.args).to eq(%i[abc def])
end
it 'is inheritable' do
subject.args %i[abc def]
c = Class.new(subject)
expect(c.args).to eq(%i[abc def])
end
it 'accepts corresponding options as default arg values' do
subject.args %i[a b]
subject.option :a, '1'
subject.option :b, '2'
expect(subject.new(nil).options.a).to eq '1'
expect(subject.new(nil).options.b).to eq '2'
expect(subject.new(nil, '3', '4').options.b).to eq '4'
expect(subject.new(nil, nil, '4').options.a).to eq nil
end
end
context 'fetcher procs' do
subject { fresh_strategy }
%w[uid info credentials extra].each do |fetcher|
describe ".#{fetcher}" do
it 'sets and retrieve a proc' do
proc = lambda { 'Hello' }
subject.send(fetcher, &proc)
expect(subject.send(fetcher)).to eq(proc)
end
end
end
end
context 'fetcher stacks' do
subject { fresh_strategy }
%w[uid info credentials extra].each do |fetcher|
describe ".#{fetcher}_stack" do
it 'is an array of called ancestral procs' do
fetchy = proc { 'Hello' }
subject.send(fetcher, &fetchy)
expect(subject.send("#{fetcher}_stack", subject.new(app))).to eq(['Hello'])
end
end
end
end
%w[request_phase].each do |abstract_method|
context abstract_method.to_s do
it 'raises a NotImplementedError' do
strat = Class.new
strat.send :include, OmniAuth::Strategy
expect { strat.new(app).send(abstract_method) }.to raise_error(NotImplementedError)
end
end
end
describe '#auth_hash' do
subject do
klass = Class.new
klass.send :include, OmniAuth::Strategy
klass.option :name, 'auth_hasher'
klass
end
let(:instance) { subject.new(app) }
it 'calls through to uid, info, credentials, and extra' do
expect(instance).to receive(:uid)
expect(instance).to receive(:info)
expect(instance).to receive(:credentials).and_return(expires: true).once
expect(instance).to receive(:extra).and_return(something: 'else').once
instance.auth_hash
end
it 'returns an AuthHash' do
allow(instance).to receive(:uid).and_return('123')
allow(instance).to receive(:info).and_return(:name => 'Hal Awesome')
allow(instance).to receive(:credentials).and_return(expires: true)
allow(instance).to receive(:extra).and_return(something: 'else')
hash = instance.auth_hash
expect(hash).to be_kind_of(OmniAuth::AuthHash)
expect(hash.uid).to eq('123')
expect(hash.info.name).to eq('Hal Awesome')
expect(hash.credentials.expires).to eq(true)
expect(hash.extra.something).to eq('else')
end
end
describe '#initialize' do
context 'options extraction' do
it 'is the last argument if the last argument is a Hash' do
expect(ExampleStrategy.new(app, :abc => 123).options[:abc]).to eq(123)
end
it 'is the default options if any are provided' do
allow(ExampleStrategy).to receive(:default_options).and_return(OmniAuth::Strategy::Options.new(:abc => 123))
expect(ExampleStrategy.new(app).options.abc).to eq(123)
end
end
context 'custom args' do
subject do
c = Class.new
c.send(:include, OmniAuth::Strategy)
end
it 'sets options based on the arguments if they are supplied' do
subject.args %i[abc def]
s = subject.new app, 123, 456
expect(s.options[:abc]).to eq(123)
expect(s.options[:def]).to eq(456)
end
end
end
describe '#call' do
it 'duplicates and calls' do
klass = Class.new
klass.send :include, OmniAuth::Strategy
instance = klass.new(app)
expect(instance).to receive(:dup).and_return(instance)
instance.call('rack.session' => {})
end
it 'raises NoSessionError if rack.session isn\'t set' do
klass = Class.new
klass.send :include, OmniAuth::Strategy
instance = klass.new(app)
expect { instance.call({}) }.to raise_error(OmniAuth::NoSessionError)
end
end
describe '#inspect' do
it 'returns the class name' do
expect(ExampleStrategy.new(app).inspect).to eq('#<ExampleStrategy>')
end
end
describe '#redirect' do
it 'uses javascript if :iframe is true' do
response = ExampleStrategy.new(app, :iframe => true).redirect('http://abc.com')
expected_body = "<script type='text/javascript' charset='utf-8'>top.location.href = 'http://abc.com';</script>"
expect(response.last).to include(expected_body)
end
end
describe '#callback_phase' do
subject do
c = Class.new
c.send(:include, OmniAuth::Strategy)
c.new(app)
end
it 'sets the auth hash' do
env = make_env
allow(subject).to receive(:env).and_return(env)
allow(subject).to receive(:auth_hash).and_return('AUTH HASH')
subject.callback_phase
expect(env['omniauth.auth']).to eq('AUTH HASH')
end
end
describe '#full_host' do
let(:strategy) { ExampleStrategy.new(app, {}) }
it 'remains calm when there is a pipe in the URL' do
strategy.call!(make_env('/whatever', 'rack.url_scheme' => 'http', 'SERVER_NAME' => 'facebook.lame', 'QUERY_STRING' => 'code=asofibasf|asoidnasd', 'SCRIPT_NAME' => '', 'SERVER_PORT' => 80))
expect { strategy.full_host }.not_to raise_error
end
end
describe '#uid' do
subject { fresh_strategy }
it "is the current class's uid if one exists" do
subject.uid { 'Hi' }
expect(subject.new(app).uid).to eq('Hi')
end
it 'inherits if it can' do
subject.uid { 'Hi' }
c = Class.new(subject)
expect(c.new(app).uid).to eq('Hi')
end
end
%w[info credentials extra].each do |fetcher|
subject { fresh_strategy }
it "is the current class's proc call if one exists" do
subject.send(fetcher) { {:abc => 123} }
expect(subject.new(app).send(fetcher)).to eq(:abc => 123)
end
it 'inherits by merging with preference for the latest class' do
subject.send(fetcher) { {:abc => 123, :def => 456} }
c = Class.new(subject)
c.send(fetcher) { {:abc => 789} }
expect(c.new(app).send(fetcher)).to eq(:abc => 789, :def => 456)
end
end
describe '#call' do
before(:all) do
@options = nil
end
let(:strategy) { ExampleStrategy.new(app, @options || {}) }
context 'omniauth.origin' do
context 'disabled' do
it 'does not set omniauth.origin' do
@options = {:origin_param => false}
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'return=/foo'))
expect(strategy.last_env['rack.session']['omniauth.origin']).to eq(nil)
end
end
context 'custom' do
it 'sets from a custom param' do
@options = {:origin_param => 'return'}
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'return=/foo'))
expect(strategy.last_env['rack.session']['omniauth.origin']).to eq('/foo')
end
end
context 'default flow' do
it 'is set on the request phase' do
expect(strategy).to receive(:fail!).with("Request Phase", kind_of(StandardError))
strategy.call(make_env('/auth/test', 'HTTP_REFERER' => 'http://example.com/origin'))
expect(strategy.last_env['rack.session']['omniauth.origin']).to eq('http://example.com/origin')
end
it 'is turned into an env variable on the callback phase' do
expect(strategy).to receive(:fail!).with("Callback Phase", kind_of(StandardError))
strategy.call(make_env('/auth/test/callback', 'rack.session' => {'omniauth.origin' => 'http://example.com/origin'}))
expect(strategy.last_env['omniauth.origin']).to eq('http://example.com/origin')
end
it 'sets from the params if provided' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'origin=/foo'))
expect(strategy.last_env['rack.session']['omniauth.origin']).to eq('/foo')
end
it 'is set on the failure env' do
expect(OmniAuth.config).to receive(:on_failure).and_return(lambda { |env| env })
@options = {:failure => :forced_fail}
strategy.call(make_env('/auth/test/callback', 'rack.session' => {'omniauth.origin' => '/awesome'}))
end
context 'with script_name' do
it 'is set on the request phase, containing full path' do
env = {'HTTP_REFERER' => 'http://example.com/sub_uri/origin', 'SCRIPT_NAME' => '/sub_uri'}
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', env))
expect(strategy.last_env['rack.session']['omniauth.origin']).to eq('http://example.com/sub_uri/origin')
end
it 'is turned into an env variable on the callback phase, containing full path' do
env = {
'rack.session' => {'omniauth.origin' => 'http://example.com/sub_uri/origin'},
'SCRIPT_NAME' => '/sub_uri'
}
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test/callback', env))
expect(strategy.last_env['omniauth.origin']).to eq('http://example.com/sub_uri/origin')
end
end
end
end
context 'default paths' do
it 'uses the default request path' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env)
end
it 'is case insensitive on request path' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/AUTH/Test'))
end
it 'is case insensitive on callback path' do
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/AUTH/TeSt/CaLlBAck'))
end
it 'uses the default callback path' do
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test/callback'))
end
it 'strips trailing spaces on request' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test/'))
end
it 'strips trailing spaces on callback' do
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test/callback/'))
end
context 'callback_url' do
it 'uses the default callback_path' do
expect(strategy).to receive(:full_host).and_return('http://example.com')
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env)
expect(strategy.callback_url).to eq('http://example.com/auth/test/callback')
end
it 'preserves the query parameters' do
allow(strategy).to receive(:full_host).and_return('http://example.com')
begin
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'id=5'))
rescue RuntimeError
end
expect(strategy.callback_url).to eq('http://example.com/auth/test/callback?id=5')
end
it 'consider script name' do
allow(strategy).to receive(:full_host).and_return('http://example.com')
begin
strategy.call(make_env('/auth/test', 'SCRIPT_NAME' => '/sub_uri'))
rescue RuntimeError
end
expect(strategy.callback_url).to eq('http://example.com/sub_uri/auth/test/callback')
end
end
end
context ':form option' do
it 'calls through to the supplied form option if one exists' do
strategy.options.form = lambda { |_env| 'Called me!' }
expect(strategy.call(make_env('/auth/test'))).to eq('Called me!')
end
it 'calls through to the app if :form => true is set as an option' do
strategy.options.form = true
expect(strategy.call(make_env('/auth/test'))).to eq(app.call(make_env('/auth/test')))
end
end
context 'dynamic paths' do
it 'runs the request phase if the custom request path evaluator is truthy' do
@options = {:request_path => lambda { |_env| true }}
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/asoufibasfi'))
end
it 'runs the callback phase if the custom callback path evaluator is truthy' do
@options = {:callback_path => lambda { |_env| true }}
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/asoufiasod'))
end
it 'provides a custom callback path if request_path evals to a string' do
strategy_instance = fresh_strategy.new(nil, :request_path => lambda { |_env| '/auth/boo/callback/22' })
expect(strategy_instance.callback_path).to eq('/auth/boo/callback/22')
end
it 'correctly reports the callback path when the custom callback path evaluator is truthy' do
strategy_instance = ExampleStrategy.new(app, :callback_path => lambda { |env| env['PATH_INFO'] == '/auth/bish/bosh/callback' })
expect(strategy_instance).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy_instance.call(make_env('/auth/bish/bosh/callback'))
expect(strategy_instance.callback_path).to eq('/auth/bish/bosh/callback')
end
end
context 'custom paths' do
it 'uses a custom request_path if one is provided' do
@options = {:request_path => '/awesome'}
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/awesome'))
end
it 'uses a custom callback_path if one is provided' do
@options = {:callback_path => '/radical'}
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/radical'))
end
context 'callback_url' do
it 'uses a custom callback_path if one is provided' do
@options = {:callback_path => '/radical'}
expect(strategy).to receive(:full_host).and_return('http://example.com')
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/radical'))
expect(strategy.callback_url).to eq('http://example.com/radical')
end
it 'preserves the query parameters' do
@options = {:callback_path => '/radical'}
allow(strategy).to receive(:full_host).and_return('http://example.com')
begin
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'id=5'))
rescue RuntimeError
end
expect(strategy.callback_url).to eq('http://example.com/radical?id=5')
end
end
end
context 'custom prefix' do
before do
@options = {:path_prefix => '/wowzers'}
end
it 'uses a custom prefix for request' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/wowzers/test'))
end
it 'uses a custom prefix for callback' do
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/wowzers/test/callback'))
end
context 'callback_url' do
it 'uses a custom prefix' do
expect(strategy).to receive(:full_host).and_return('http://example.com')
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/wowzers/test'))
expect(strategy.callback_url).to eq('http://example.com/wowzers/test/callback')
end
it 'preserves the query parameters' do
allow(strategy).to receive(:full_host).and_return('http://example.com')
begin
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'id=5'))
rescue RuntimeError
end
expect(strategy.callback_url).to eq('http://example.com/wowzers/test/callback?id=5')
end
end
end
context 'with relative url root' do
let(:props) { {'SCRIPT_NAME' => '/myapp'} }
it 'accepts the request' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', props))
expect(strategy.request_path).to eq('/myapp/auth/test')
end
it 'accepts the callback' do
expect(strategy).to receive(:fail!).with('Callback Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test/callback', props))
end
context 'callback_url' do
it 'redirects to the correctly prefixed callback' do
expect(strategy).to receive(:full_host).and_return('http://example.com')
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test', props))
expect(strategy.callback_url).to eq('http://example.com/myapp/auth/test/callback')
end
end
context 'custom request' do
before do
@options = {:request_path => '/myapp/override', :callback_path => '/myapp/override/callback'}
end
it 'does not prefix a custom request path' do
expect(strategy).to receive(:full_host).and_return('http://example.com')
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
expect(strategy.request_path).to eq('/myapp/override')
strategy.call(make_env('/override', props))
expect(strategy.callback_url).to eq('http://example.com/myapp/override/callback')
end
end
context 'error during call_app!' do
class OtherPhaseStrategy < ExampleStrategy
def other_phase
call_app!
end
end
class AppError < StandardError; end
let(:app) { ->(_env) { raise(AppError.new('Some error in the app!')) } }
let(:strategy) { OtherPhaseStrategy.new(app) }
it 'raises the application error' do
expect { strategy.call(make_env('/some/path')) }.to raise_error(AppError, 'Some error in the app!')
end
end
context 'error during auth phase' do
class SomeStrategy < ExampleStrategy
def request_phase
raise AuthError.new('Some error in authentication')
end
end
class AuthError < StandardError; end
let(:strategy) { SomeStrategy.new(app) }
it 'passes the error to fail!()' do
expect(strategy).to receive(:fail!).with('Some error in authentication', kind_of(AuthError))
strategy.call(make_env('/auth/test', props))
end
end
end
context 'request method restriction' do
before(:context) do
OmniAuth.config.allowed_request_methods = %i[put post]
end
it 'does not allow a request method of the wrong type' do
expect { strategy.call(make_env('/auth/test', 'REQUEST_METHOD' => 'GET')) }.not_to raise_error
end
it 'allows a request method of the correct type' do
expect(strategy).to receive(:fail!).with('Request Phase', kind_of(StandardError))
strategy.call(make_env('/auth/test'))
end
after(:context) do
OmniAuth.config.allowed_request_methods = %i[post]
end
end
context 'receiving an OPTIONS request' do
shared_examples_for 'an OPTIONS request' do
it 'responds with 200' do
expect(response[0]).to eq(200)
end
it 'sets the Allow header properly' do
expect(response[1]['Allow']).to eq('POST')
end
end
context 'to the request path' do
let(:response) { strategy.call(make_env('/auth/test', 'REQUEST_METHOD' => 'OPTIONS')) }
it_behaves_like 'an OPTIONS request'
end
context 'to the request path' do
let(:response) { strategy.call(make_env('/auth/test/callback', 'REQUEST_METHOD' => 'OPTIONS')) }
it_behaves_like 'an OPTIONS request'
end
context 'to some other path' do
it 'does not short-circuit the request' do
env = make_env('/other', 'REQUEST_METHOD' => 'OPTIONS')
expect(strategy.call(env)).to eq(app.call(env))
end
end
end
context 'options mutation' do
before do
@options = {:dup => true}
end
context 'in request phase' do
it 'does not affect original options' do
@options[:test_option] = true
@options[:mutate_on_request] = proc { |options| options.delete(:test_option) }
strategy.call(make_env)
expect(strategy.options).to have_key(:test_option)
end
it 'does not affect deep options' do
@options[:deep_option] = {:test_option => true}
@options[:mutate_on_request] = proc { |options| options[:deep_option].delete(:test_option) }
strategy.call(make_env)
expect(strategy.options[:deep_option]).to have_key(:test_option)
end
end
context 'in callback phase' do
it 'does not affect original options' do
@options[:test_option] = true
@options[:mutate_on_callback] = proc { |options| options.delete(:test_option) }
strategy.call(make_env('/auth/test/callback', 'REQUEST_METHOD' => 'POST'))
expect(strategy.options).to have_key(:test_option)
end
it 'does not affect deep options' do
@options[:deep_option] = {:test_option => true}
@options[:mutate_on_callback] = proc { |options| options[:deep_option].delete(:test_option) }
strategy.call(make_env('/auth/test/callback', 'REQUEST_METHOD' => 'POST'))
expect(strategy.options[:deep_option]).to have_key(:test_option)
end
end
end
context 'test mode' do
let(:app) do
# In test mode, the underlying app shouldn't be called on request phase.
lambda { |_env| [404, {'Content-Type' => 'text/html'}, []] }
end
before do
OmniAuth.config.test_mode = true
end
it 'short circuits the request phase entirely' do
response = strategy.call(make_env)
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/auth/test/callback')
end
it "doesn't short circuit the request if request method is not allowed" do
response = strategy.call(make_env('/auth/test', 'REQUEST_METHOD' => 'DELETE'))
expect(response[0]).to eq(404)
end
it 'is case insensitive on request path' do
expect(strategy.call(make_env('/AUTH/Test'))[0]).to eq(302)
end
it 'respects SCRIPT_NAME (a.k.a. BaseURI)' do
response = strategy.call(make_env('/auth/test', 'SCRIPT_NAME' => '/sub_uri'))
expect(response[1]['Location']).to eq('/sub_uri/auth/test/callback')
end
it 'redirects on failure' do
response = OmniAuth.config.on_failure.call(make_env('/auth/test', 'omniauth.error.type' => 'error'))
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/auth/failure?message=error')
end
it 'respects SCRIPT_NAME (a.k.a. BaseURI) on failure' do
response = OmniAuth.config.on_failure.call(make_env('/auth/test', 'SCRIPT_NAME' => '/sub_uri', 'omniauth.error.type' => 'error'))
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/sub_uri/auth/failure?message=error')
end
it 'is case insensitive on callback path' do
expect(strategy.call(make_env('/AUTH/TeSt/CaLlBAck')).first).to eq(strategy.call(make_env('/auth/test/callback')).first)
end
it 'maintains host and port' do
response = strategy.call(make_env('/auth/test', 'rack.url_scheme' => 'http', 'SERVER_NAME' => 'example.org', 'SERVER_PORT' => 9292))
expect(response[1]['Location']).to eq('http://example.org:9292/auth/test/callback')
end
it 'maintains query string parameters' do
response = strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'cheese=stilton'))
expect(response[1]['Location']).to eq('/auth/test/callback?cheese=stilton')
end
it 'does not short circuit requests outside of authentication' do
expect(strategy.call(make_env('/'))).to eq(app.call(make_env('/')))
end
it 'responds with the default hash if none is set' do
OmniAuth.config.mock_auth[:test] = nil
strategy.call make_env('/auth/test/callback')
expect(strategy.env['omniauth.auth']['uid']).to eq('1234')
end
it 'responds with a provider-specific hash if one is set' do
OmniAuth.config.mock_auth[:test] = {
'uid' => 'abc'
}
strategy.call make_env('/auth/test/callback')
expect(strategy.env['omniauth.auth']['uid']).to eq('abc')
end
it 'simulates login failure if mocked data is set as a symbol' do
OmniAuth.config.mock_auth[:test] = :invalid_credentials
strategy.call make_env('/auth/test/callback')
expect(strategy.env['omniauth.error.type']).to eq(:invalid_credentials)
end
context 'omniauth.origin' do
context 'disabled' do
it 'does not set omniauth.origin' do
@options = {:origin_param => false}
strategy.call(make_env('/auth/test', 'HTTP_REFERER' => 'http://example.com/origin'))
expect(strategy.env['rack.session']['omniauth.origin']).to be_nil
end
end
context 'default flow' do
it 'sets omniauth.origin to the HTTP_REFERER on the request phase by default' do
strategy.call(make_env('/auth/test', 'HTTP_REFERER' => 'http://example.com/origin'))
expect(strategy.env['rack.session']['omniauth.origin']).to eq('http://example.com/origin')
end
it 'sets omniauth.origin from the params if provided' do
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'origin=/foo'))
expect(strategy.env['rack.session']['omniauth.origin']).to eq('/foo')
end
end
context 'custom' do
it 'sets omniauth.origin from a custom param' do
@options = {:origin_param => 'return'}
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'return=/foo'))
expect(strategy.env['rack.session']['omniauth.origin']).to eq('/foo')
end
end
end
it 'turns omniauth.origin into an env variable on the callback phase' do
OmniAuth.config.mock_auth[:test] = {}
strategy.call(make_env('/auth/test/callback', 'rack.session' => {'omniauth.origin' => 'http://example.com/origin'}))
expect(strategy.env['omniauth.origin']).to eq('http://example.com/origin')
end
it 'does not override omniauth.origin if already set on the callback phase' do
strategy.call(make_env('/auth/test/callback',
'rack.session' => {'omniauth.origin' => 'http://example.com/origin'},
'omniauth.origin' => '/foo'))
expect(strategy.env['omniauth.origin']).to eq('/foo')
expect(strategy.env['rack.session']['omniauth.origin']).to be_nil
end
it 'executes callback hook on the callback phase' do
OmniAuth.config.mock_auth[:test] = {}
OmniAuth.config.before_callback_phase do |env|
env['foobar'] = 'baz'
end
strategy.call(make_env('/auth/test/callback', 'rack.session' => {'omniauth.origin' => 'http://example.com/origin'}))
expect(strategy.env['foobar']).to eq('baz')
end
it 'sets omniauth.params with query params on the request phase' do
OmniAuth.config.mock_auth[:test] = {}
strategy.call(make_env('/auth/test', 'QUERY_STRING' => 'foo=bar'))
expect(strategy.env['rack.session']['omniauth.params']).to eq('foo' => 'bar')
end
it 'does not set body parameters of POST request on the request phase' do
OmniAuth.config.mock_auth[:test] = {}
props = {
'REQUEST_METHOD' => 'POST',
'rack.input' => StringIO.new('foo=bar')
}
strategy.call(make_env('/auth/test', props))
expect(strategy.env['rack.session']['omniauth.params']).to eq({})
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | true |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/failure_endpoint_spec.rb | spec/omniauth/failure_endpoint_spec.rb | require 'helper'
describe OmniAuth::FailureEndpoint do
subject { OmniAuth::FailureEndpoint }
context 'raise-out environment' do
before do
@rack_env = ENV['RACK_ENV']
ENV['RACK_ENV'] = 'test'
@default = OmniAuth.config.failure_raise_out_environments
OmniAuth.config.failure_raise_out_environments = ['test']
end
it 'raises out the error' do
expect do
subject.call('omniauth.error' => StandardError.new('Blah'))
end.to raise_error(StandardError, 'Blah')
end
it 'raises out an OmniAuth::Error if no omniauth.error is set' do
expect { subject.call('omniauth.error.type' => 'example') }.to raise_error(OmniAuth::Error, 'example')
end
after do
ENV['RACK_ENV'] = @rack_env
OmniAuth.config.failure_raise_out_environments = @default
end
end
context 'non-raise-out environment' do
let(:env) do
{'omniauth.error.type' => 'invalid_request', 'omniauth.error.strategy' => ExampleStrategy.new({})}
end
it 'is a redirect' do
status, = *subject.call(env)
expect(status).to eq(302)
end
it 'includes the SCRIPT_NAME' do
_, head, = *subject.call(env.merge('SCRIPT_NAME' => '/random'))
expect(head['Location']).to eq('/random/auth/failure?message=invalid_request&strategy=test')
end
it 'respects the globally configured path prefix' do
allow(OmniAuth.config).to receive(:path_prefix).and_return('/boo')
_, head, = *subject.call(env)
expect(head['Location']).to eq('/boo/failure?message=invalid_request&strategy=test')
end
it 'respects the custom path prefix configured on the strategy' do
env['omniauth.error.strategy'] = ExampleStrategy.new({}, path_prefix: "/some/custom/path")
_, head, = *subject.call(env)
expect(head['Location']).to eq('/some/custom/path/failure?message=invalid_request&strategy=test')
end
it 'includes the origin (escaped) if one is provided' do
env['omniauth.origin'] = '/origin-example'
_, head, = *subject.call(env)
expect(head['Location']).to be_include('&origin=%2Forigin-example')
end
it 'escapes the message key' do
_, head = *subject.call(env.merge('omniauth.error.type' => 'Connection refused!'))
expect(head['Location']).to be_include('message=Connection+refused%21')
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/builder_spec.rb | spec/omniauth/builder_spec.rb | require 'helper'
describe OmniAuth::Builder do
describe '#provider' do
it 'translates a symbol to a constant' do
expect(OmniAuth::Strategies).to receive(:const_get).with('MyStrategy', false).and_return(Class.new)
OmniAuth::Builder.new(nil) do
provider :my_strategy
end
end
it 'accepts a class' do
class ExampleClass; end
expect do
OmniAuth::Builder.new(nil) do
provider ::ExampleClass
end
end.not_to raise_error
end
it "raises a helpful LoadError message if it can't find the class" do
expect do
OmniAuth::Builder.new(nil) do
provider :lorax
end
end.to raise_error(LoadError, 'Could not find matching strategy for :lorax. You may need to install an additional gem (such as omniauth-lorax).')
end
it "doesn't translate a symbol to a top-level constant" do
class MyStrategy; end
expect do
OmniAuth::Builder.new(nil) do
provider :my_strategy
end
end.to raise_error(LoadError, 'Could not find matching strategy for :my_strategy. You may need to install an additional gem (such as omniauth-my_strategy).')
end
end
describe '#options' do
it 'merges provided options in' do
k = Class.new
b = OmniAuth::Builder.new(nil)
expect(b).to receive(:use).with(k, :foo => 'bar', :baz => 'tik')
b.options :foo => 'bar'
b.provider k, :baz => 'tik'
end
it 'adds an argument if no options are provided' do
k = Class.new
b = OmniAuth::Builder.new(nil)
expect(b).to receive(:use).with(k, :foo => 'bar')
b.options :foo => 'bar'
b.provider k
end
end
describe '#on_failure' do
it 'passes the block to the config' do
prok = proc {}
with_config_reset(:on_failure) do
OmniAuth::Builder.new(nil).on_failure(&prok)
expect(OmniAuth.config.on_failure).to eq(prok)
end
end
end
describe '#before_options_phase' do
it 'passes the block to the config' do
prok = proc {}
with_config_reset(:before_options_phase) do
OmniAuth::Builder.new(nil).before_options_phase(&prok)
expect(OmniAuth.config.before_options_phase).to eq(prok)
end
end
end
describe '#before_request_phase' do
it 'passes the block to the config' do
prok = proc {}
with_config_reset(:before_request_phase) do
OmniAuth::Builder.new(nil).before_request_phase(&prok)
expect(OmniAuth.config.before_request_phase).to eq(prok)
end
end
end
describe '#after_request_phase' do
it 'passes the block to the config' do
prok = proc {}
with_config_reset(:after_request_phase) do
OmniAuth::Builder.new(nil).after_request_phase(&prok)
expect(OmniAuth.config.after_request_phase).to eq(prok)
end
end
end
describe '#before_callback_phase' do
it 'passes the block to the config' do
prok = proc {}
with_config_reset(:before_callback_phase) do
OmniAuth::Builder.new(nil).before_callback_phase(&prok)
expect(OmniAuth.config.before_callback_phase).to eq(prok)
end
end
end
describe '#configure' do
it 'passes the block to the config' do
prok = proc {}
allow(OmniAuth).to receive(:configure).and_call_original
OmniAuth::Builder.new(nil).configure(&prok)
expect(OmniAuth).to have_received(:configure) do |&block|
expect(block).to eq(prok)
end
end
end
describe '#call' do
it 'passes env to to_app.call' do
app = lambda { |env| [200, {}, env['CUSTOM_ENV_VALUE']] }
builder = OmniAuth::Builder.new(app)
env = {'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/some/path', 'CUSTOM_ENV_VALUE' => 'VALUE'}
expect(builder.call(env)).to eq([200, {}, 'VALUE'])
end
end
def with_config_reset(option)
old_config = OmniAuth.config.send(option)
yield
OmniAuth.config.send("#{option}=", old_config)
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/auth_hash_spec.rb | spec/omniauth/auth_hash_spec.rb | require 'helper'
describe OmniAuth::AuthHash do
subject { OmniAuth::AuthHash.new }
it 'converts a supplied info key into an InfoHash object' do
subject.info = {:first_name => 'Awesome'}
expect(subject.info).to be_kind_of(OmniAuth::AuthHash::InfoHash)
expect(subject.info.first_name).to eq('Awesome')
end
it 'does not try to parse `string` as InfoHash' do
subject.weird_field = {:info => 'string'}
expect(subject.weird_field.info).to eq 'string'
end
it 'has a subkey_class' do
expect(OmniAuth::AuthHash.subkey_class).to eq Hashie::Mash
end
describe '#valid?' do
subject { OmniAuth::AuthHash.new(:uid => '123', :provider => 'example', :info => {:name => 'Steven'}) }
it 'is valid with the right parameters' do
expect(subject).to be_valid
end
it 'requires a uid' do
subject.uid = nil
expect(subject).not_to be_valid
end
it 'requires a provider' do
subject.provider = nil
expect(subject).not_to be_valid
end
it 'requires a name in the user info hash' do
subject.info.name = nil
expect(subject).not_to be_valid
end
end
describe '#name' do
subject do
OmniAuth::AuthHash.new(:info => {
:name => 'Phillip J. Fry',
:first_name => 'Phillip',
:last_name => 'Fry',
:nickname => 'meatbag',
:email => 'fry@planetexpress.com'
})
end
it 'defaults to the name key' do
expect(subject.info.name).to eq('Phillip J. Fry')
end
it 'falls back to go to first_name last_name concatenation' do
subject.info.name = nil
expect(subject.info.name).to eq('Phillip Fry')
end
it 'displays only a first or last name if only that is available' do
subject.info.name = nil
subject.info.first_name = nil
expect(subject.info.name).to eq('Fry')
end
it 'displays the nickname if no name, first, or last is available' do
subject.info.name = nil
%w[first_name last_name].each { |k| subject.info[k] = nil }
expect(subject.info.name).to eq('meatbag')
end
it 'displays the email if no name, first, last, or nick is available' do
subject.info.name = nil
%w[first_name last_name nickname].each { |k| subject.info[k] = nil }
expect(subject.info.name).to eq('fry@planetexpress.com')
end
end
describe '#to_hash' do
subject { OmniAuth::AuthHash.new(:uid => '123', :provider => 'test', :name => 'Example User') }
let(:hash) { subject.to_hash }
it 'is a plain old hash' do
expect(hash.class).to eq(::Hash)
end
it 'has string keys' do
expect(hash.keys).to be_include('uid')
end
it 'converts an info hash as well' do
subject.info = {:first_name => 'Example', :last_name => 'User'}
expect(subject.info.class).to eq(OmniAuth::AuthHash::InfoHash)
expect(subject.to_hash['info'].class).to eq(::Hash)
end
it 'supplies the calculated name in the converted hash' do
subject.info = {:first_name => 'Examplar', :last_name => 'User'}
expect(hash['info']['name']).to eq('Examplar User')
end
it "does not pollute the URL hash with 'name' etc" do
subject.info = {'urls' => {'Homepage' => 'http://homepage.com'}}
expect(subject.to_hash['info']['urls']).to eq('Homepage' => 'http://homepage.com')
end
end
describe OmniAuth::AuthHash::InfoHash do
describe '#valid?' do
it 'is valid if there is a name' do
expect(OmniAuth::AuthHash::InfoHash.new(:name => 'Awesome')).to be_valid
end
end
it 'has a subkey_class' do
expect(OmniAuth::AuthHash::InfoHash.subkey_class).to eq Hashie::Mash
end
require 'hashie/version'
if Gem::Version.new(Hashie::VERSION) >= Gem::Version.new('3.5.1')
context 'with Hashie 3.5.1+' do
around(:each) do |example|
original_logger = Hashie.logger
example.run
Hashie.logger = original_logger
end
it 'does not log anything in Hashie 3.5.1+' do
logger = double('Logger')
expect(logger).not_to receive(:warn)
Hashie.logger = logger
subject.name = 'test'
end
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/key_store_spec.rb | spec/omniauth/key_store_spec.rb | require 'helper'
RSpec.describe OmniAuth::KeyStore do
let(:logger) { double('Logger') }
around(:each) do |example|
patched = monkey_patch_logger
example.run
remove_logger(patched)
end
context 'on Hashie < 3.5.0' do
let(:version) { '3.4.0' }
it 'does not log anything to the console' do
stub_const('Hashie::VERSION', version)
OmniAuth::KeyStore.override_logging
expect(logger).not_to receive(:info)
OmniAuth::KeyStore.new(:id => 1234)
end
end
context 'on Hashie 3.5.0 and 3.5.1' do
let(:version) { '3.5.0' }
it 'does not log anything to the console' do
stub_const('Hashie::VERSION', version)
allow(OmniAuth::KeyStore).to receive(:respond_to?).with(:disable_warnings).and_return(false)
OmniAuth::KeyStore.override_logging
expect(logger).not_to receive(:info)
OmniAuth::KeyStore.new(:id => 1234)
end
end
context 'on Hashie 3.5.2+' do
let(:version) { '3.5.2' }
around(:each) do |example|
patching = monkey_patch_unreleased_interface
example.run
remove_monkey_patch(patching)
end
it 'does not log anything to the console' do
stub_const('Hashie::VERSION', version)
OmniAuth::KeyStore.override_logging
expect(logger).not_to receive(:info)
OmniAuth::KeyStore.new(:id => 1234)
end
end
def monkey_patch_unreleased_interface
return false if OmniAuth::KeyStore.class.respond_to?(:disable_warnings, true)
OmniAuth::KeyStore.define_singleton_method(:disable_warnings) {}
OmniAuth::KeyStore.define_singleton_method(:log_built_in_message) { |*| }
true
end
def monkey_patch_logger
return unless Hashie.respond_to?(:logger)
original_logger = Hashie.logger
Hashie.logger = logger
original_logger
end
def remove_logger(logger)
return unless logger
Hashie.logger = logger
end
def remove_monkey_patch(perform)
return unless perform
OmniAuth::KeyStore.singleton_class.__send__(:remove_method, :disable_warnings)
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/spec/omniauth/strategies/developer_spec.rb | spec/omniauth/strategies/developer_spec.rb | require 'helper'
describe OmniAuth::Strategies::Developer do
let(:app) do
Rack::Builder.new do |b|
b.use Rack::Session::Cookie, :secret => 'abc123'
b.use OmniAuth::Strategies::Developer
b.run lambda { |_env| [200, {}, ['Not Found']] }
end.to_app
end
context 'request phase' do
before(:each) { post '/auth/developer' }
it 'displays a form' do
expect(last_response.status).to eq(200)
expect(last_response.body).to be_include('<form')
end
it 'has the callback as the action for the form' do
expect(last_response.body).to be_include("action='/auth/developer/callback'")
end
it 'has a text field for each of the fields' do
expect(last_response.body.scan('<input').size).to eq(2)
end
end
context 'callback phase' do
let(:auth_hash) { last_request.env['omniauth.auth'] }
context 'with default options' do
before do
get '/auth/developer/callback', :name => 'Example User', :email => 'user@example.com'
end
it 'sets the name in the auth hash' do
expect(auth_hash.info.name).to eq('Example User')
end
it 'sets the email in the auth hash' do
expect(auth_hash.info.email).to eq('user@example.com')
end
it 'sets the uid to the email' do
expect(auth_hash.uid).to eq('user@example.com')
end
end
context 'with custom options' do
let(:app) do
Rack::Builder.new do |b|
b.use Rack::Session::Cookie, :secret => 'abc123'
b.use OmniAuth::Strategies::Developer, :fields => %i[first_name last_name], :uid_field => :last_name
b.run lambda { |_env| [200, {}, ['Not Found']] }
end.to_app
end
before do
@options = {:uid_field => :last_name, :fields => %i[first_name last_name]}
get '/auth/developer/callback', :first_name => 'Example', :last_name => 'User'
end
it 'sets info fields properly' do
expect(auth_hash.info.name).to eq('Example User')
end
it 'sets the uid properly' do
expect(auth_hash.uid).to eq('User')
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth.rb | lib/omniauth.rb | # TODO: Fixed in https://github.com/rack/rack/pull/1610 for Rack 3
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
require 'delegate'
end
require 'rack'
require 'singleton'
require 'logger'
module OmniAuth
class Error < StandardError; end
module Strategies
autoload :Developer, 'omniauth/strategies/developer'
end
autoload :Builder, 'omniauth/builder'
autoload :Strategy, 'omniauth/strategy'
autoload :Test, 'omniauth/test'
autoload :Form, 'omniauth/form'
autoload :AuthHash, 'omniauth/auth_hash'
autoload :FailureEndpoint, 'omniauth/failure_endpoint'
autoload :AuthenticityTokenProtection, 'omniauth/authenticity_token_protection'
def self.strategies
@strategies ||= []
end
class Configuration
include Singleton
def self.default_logger
logger = Logger.new(STDOUT)
logger.progname = 'omniauth'
logger
end
def self.defaults # rubocop:disable MethodLength
@defaults ||= {
:camelizations => {},
:path_prefix => '/auth',
:on_failure => OmniAuth::FailureEndpoint,
:failure_raise_out_environments => ['development'],
:request_validation_phase => OmniAuth::AuthenticityTokenProtection,
:before_request_phase => nil,
:after_request_phase => nil,
:before_callback_phase => nil,
:before_options_phase => nil,
:form_css => Form::DEFAULT_CSS,
:test_mode => false,
:logger => default_logger,
:allowed_request_methods => %i[post],
:mock_auth => {:default => AuthHash.new('provider' => 'default', 'uid' => '1234', 'info' => {'name' => 'Example User'})},
:silence_get_warning => false
}
end
def initialize
self.class.defaults.each_pair { |k, v| send("#{k}=", v) }
end
def on_failure(&block)
if block_given?
@on_failure = block
else
@on_failure
end
end
def before_callback_phase(&block)
if block_given?
@before_callback_phase = block
else
@before_callback_phase
end
end
def before_options_phase(&block)
if block_given?
@before_options_phase = block
else
@before_options_phase
end
end
def request_validation_phase(&block)
if block_given?
@request_validation_phase = block
else
@request_validation_phase
end
end
def before_request_phase(&block)
if block_given?
@before_request_phase = block
else
@before_request_phase
end
end
def after_request_phase(&block)
if block_given?
@after_request_phase = block
else
@after_request_phase
end
end
def add_mock(provider, original = {})
# Create key-stringified new hash from given auth hash
mock = {}
original.each_pair do |key, val|
mock[key.to_s] = if val.is_a? Hash
Hash[val.each_pair { |k, v| [k.to_s, v] }]
else
val
end
end
# Merge with the default mock and ensure provider is correct.
mock = mock_auth[:default].dup.merge(mock)
mock['provider'] = provider.to_s
# Add it to the mocks.
mock_auth[provider.to_sym] = mock
end
# This is a convenience method to be used by strategy authors
# so that they can add special cases to the camelization utility
# method that allows OmniAuth::Builder to work.
#
# @param name [String] The underscored name, e.g. `oauth`
# @param camelized [String] The properly camelized name, e.g. 'OAuth'
def add_camelization(name, camelized)
camelizations[name.to_s] = camelized.to_s
end
attr_writer :on_failure, :before_callback_phase, :before_options_phase, :before_request_phase, :after_request_phase, :request_validation_phase
attr_accessor :failure_raise_out_environments, :path_prefix, :allowed_request_methods, :form_css,
:test_mode, :mock_auth, :full_host, :camelizations, :logger, :silence_get_warning
end
def self.config
Configuration.instance
end
def self.configure
yield config
end
def self.logger
config.logger
end
def self.mock_auth_for(provider)
config.mock_auth[provider.to_sym] || config.mock_auth[:default]
end
module Utils
module_function # rubocop:disable Layout/IndentationWidth
def form_css
"<style type='text/css'>#{OmniAuth.config.form_css}</style>"
end
def deep_merge(hash, other_hash)
target = hash.dup
other_hash.each_key do |key|
if other_hash[key].is_a?(::Hash) && hash[key].is_a?(::Hash)
target[key] = deep_merge(target[key], other_hash[key])
next
end
target[key] = other_hash[key]
end
target
end
def camelize(word, first_letter_in_uppercase = true)
return OmniAuth.config.camelizations[word.to_s] if OmniAuth.config.camelizations[word.to_s]
if first_letter_in_uppercase
word.to_s.gsub(%r{/(.?)}) { '::' + Regexp.last_match[1].upcase }.gsub(/(^|_)(.)/) { Regexp.last_match[2].upcase }
else
camelize(word).tap { |w| w[0] = w[0].downcase }
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/test.rb | lib/omniauth/test.rb | module OmniAuth
# Support for testing OmniAuth strategies.
module Test
autoload :PhonySession, 'omniauth/test/phony_session'
autoload :StrategyMacros, 'omniauth/test/strategy_macros'
autoload :StrategyTestCase, 'omniauth/test/strategy_test_case'
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/authenticity_token_protection.rb | lib/omniauth/authenticity_token_protection.rb | require 'rack-protection'
module OmniAuth
class AuthenticityError < StandardError; end
class AuthenticityTokenProtection < Rack::Protection::AuthenticityToken
def initialize(options = {})
@options = default_options.merge(options)
end
def self.call(env)
new.call!(env)
end
def call!(env)
return if accepts?(env)
instrument env
react env
end
alias_method :call, :call!
private
def deny(_env)
OmniAuth.logger.send(:warn, "Attack prevented by #{self.class}")
raise AuthenticityError.new(options[:message])
end
alias default_reaction deny
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/version.rb | lib/omniauth/version.rb | module OmniAuth
VERSION = '2.1.4'.freeze
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/strategy.rb | lib/omniauth/strategy.rb | require 'omniauth/key_store'
module OmniAuth
class NoSessionError < StandardError; end
# The Strategy is the base unit of OmniAuth's ability to
# wrangle multiple providers. Each strategy provided by
# OmniAuth includes this mixin to gain the default functionality
# necessary to be compatible with the OmniAuth library.
module Strategy # rubocop:disable ModuleLength
def self.included(base)
OmniAuth.strategies << base
base.extend ClassMethods
base.class_eval do
option :setup, false
option :skip_info, false
option :origin_param, 'origin'
end
end
module ClassMethods
# Returns an inherited set of default options set at the class-level
# for each strategy.
def default_options
# existing = superclass.default_options if superclass.respond_to?(:default_options)
existing = superclass.respond_to?(:default_options) ? superclass.default_options : {}
@default_options ||= OmniAuth::Strategy::Options.new(existing)
end
# This allows for more declarative subclassing of strategies by allowing
# default options to be set using a simple configure call.
#
# @param options [Hash] If supplied, these will be the default options (deep-merged into the superclass's default options).
# @yield [Options] The options Mash that allows you to set your defaults as you'd like.
#
# @example Using a yield to configure the default options.
#
# class MyStrategy
# include OmniAuth::Strategy
#
# configure do |c|
# c.foo = 'bar'
# end
# end
#
# @example Using a hash to configure the default options.
#
# class MyStrategy
# include OmniAuth::Strategy
# configure foo: 'bar'
# end
def configure(options = nil)
if block_given?
yield default_options
else
default_options.deep_merge!(options)
end
end
# Directly declare a default option for your class. This is a useful from
# a documentation perspective as it provides a simple line-by-line analysis
# of the kinds of options your strategy provides by default.
#
# @param name [Symbol] The key of the default option in your configuration hash.
# @param value [Object] The value your object defaults to. Nil if not provided.
#
# @example
#
# class MyStrategy
# include OmniAuth::Strategy
#
# option :foo, 'bar'
# option
# end
def option(name, value = nil)
default_options[name] = value
end
# Sets (and retrieves) option key names for initializer arguments to be
# recorded as. This takes care of 90% of the use cases for overriding
# the initializer in OmniAuth Strategies.
def args(args = nil)
if args
@args = Array(args)
return
end
existing = superclass.respond_to?(:args) ? superclass.args : []
(instance_variable_defined?(:@args) && @args) || existing
end
%w[uid info extra credentials].each do |fetcher|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
attr_reader :#{fetcher}_proc
private :#{fetcher}_proc
def #{fetcher}(&block)
return #{fetcher}_proc unless block_given?
@#{fetcher}_proc = block
end
def #{fetcher}_stack(context)
compile_stack(self.ancestors, :#{fetcher}, context)
end
RUBY
end
def compile_stack(ancestors, method, context)
stack = ancestors.inject([]) do |a, ancestor|
a << context.instance_eval(&ancestor.send(method)) if ancestor.respond_to?(method) && ancestor.send(method)
a
end
stack.reverse!
end
end
attr_reader :app, :env, :options, :response
# Initializes the strategy by passing in the Rack endpoint,
# the unique URL segment name for this strategy, and any
# additional arguments. An `options` hash is automatically
# created from the last argument if it is a hash.
#
# @param app [Rack application] The application on which this middleware is applied.
#
# @overload new(app, options = {})
# If nothing but a hash is supplied, initialized with the supplied options
# overriding the strategy's default options via a deep merge.
# @overload new(app, *args, options = {})
# If the strategy has supplied custom arguments that it accepts, they may
# will be passed through and set to the appropriate values.
#
# @yield [Options] Yields options to block for further configuration.
def initialize(app, *args, &block) # rubocop:disable UnusedMethodArgument
@app = app
@env = nil
@options = self.class.default_options.dup
options.deep_merge!(args.pop) if args.last.is_a?(Hash)
options[:name] ||= self.class.to_s.split('::').last.downcase
self.class.args.each do |arg|
break if args.empty?
options[arg] = args.shift
end
# Make sure that all of the args have been dealt with, otherwise error out.
raise(ArgumentError.new("Received wrong number of arguments. #{args.inspect}")) unless args.empty?
yield options if block_given?
end
def inspect
"#<#{self.class}>"
end
# Direct access to the OmniAuth logger, automatically prefixed
# with this strategy's name.
#
# @example
# log :warn, "This is a warning."
def log(level, message)
OmniAuth.logger.send(level, "(#{name}) #{message}")
end
# Duplicates this instance and runs #call! on it.
# @param [Hash] The Rack environment.
def call(env)
dup.call!(env)
end
# The logic for dispatching any additional actions that need
# to be taken. For instance, calling the request phase if
# the request path is recognized.
#
# @param env [Hash] The Rack environment.
def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity
unless env['rack.session']
error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')
raise(error)
end
@env = env
warn_if_using_get_on_request_path
@env['omniauth.strategy'] = self if on_auth_path?
return mock_call!(env) if OmniAuth.config.test_mode
begin
return options_call if on_auth_path? && options_request?
return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)
return callback_call if on_callback_path?
return other_phase if respond_to?(:other_phase)
rescue StandardError => e
raise e if env.delete('omniauth.error.app')
return fail!(e.message, e)
end
@app.call(env)
end
def warn_if_using_get_on_request_path
return unless on_request_path?
return unless OmniAuth.config.allowed_request_methods.include?(:get)
return if OmniAuth.config.silence_get_warning
log :warn, <<-WARN
You are using GET as an allowed request method for OmniAuth. This may leave
you open to CSRF attacks. As of v2.0.0, OmniAuth by default allows only POST
to its own routes. You should review the following resources to guide your
mitigation:
https://github.com/omniauth/omniauth/wiki/Resolving-CVE-2015-9284
https://github.com/omniauth/omniauth/issues/960
https://nvd.nist.gov/vuln/detail/CVE-2015-9284
https://github.com/omniauth/omniauth/pull/809
You can ignore this warning by setting:
OmniAuth.config.silence_get_warning = true
WARN
end
# Responds to an OPTIONS request.
def options_call
OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase
verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')
[200, {'Allow' => verbs}, []]
end
# Performs the steps necessary to run the request phase of a strategy.
def request_call # rubocop:disable CyclomaticComplexity, MethodLength, PerceivedComplexity
setup_phase
log :debug, 'Request phase initiated.'
# store query params from the request url, extracted in the callback_phase
session['omniauth.params'] = request.GET
OmniAuth.config.request_validation_phase.call(env) if OmniAuth.config.request_validation_phase
OmniAuth.config.before_request_phase.call(env) if OmniAuth.config.before_request_phase
result = if options.form.respond_to?(:call)
log :debug, 'Rendering form from supplied Rack endpoint.'
options.form.call(env)
elsif options.form
log :debug, 'Rendering form from underlying application.'
call_app!
elsif !options.origin_param
request_phase
else
if request.params[options.origin_param]
env['rack.session']['omniauth.origin'] = request.params[options.origin_param]
elsif env['HTTP_REFERER'] && !env['HTTP_REFERER'].match(/#{request_path}$/)
env['rack.session']['omniauth.origin'] = env['HTTP_REFERER']
end
request_phase
end
OmniAuth.config.after_request_phase.call(env) if OmniAuth.config.after_request_phase
result
rescue OmniAuth::AuthenticityError => e
fail!(:authenticity_error, e)
end
# Performs the steps necessary to run the callback phase of a strategy.
def callback_call
setup_phase
log :debug, 'Callback phase initiated.'
@env['omniauth.origin'] = session.delete('omniauth.origin')
@env['omniauth.origin'] = nil if env['omniauth.origin'] == ''
@env['omniauth.params'] = session.delete('omniauth.params') || {}
OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase
callback_phase
end
# Returns true if the environment recognizes either the
# request or callback path.
def on_auth_path?
on_request_path? || on_callback_path?
end
def on_request_path?
if options[:request_path].respond_to?(:call)
options[:request_path].call(env)
else
on_path?(request_path)
end
end
def on_callback_path?
on_path?(callback_path)
end
def on_path?(path)
current_path.casecmp(path).zero?
end
def options_request?
request.request_method == 'OPTIONS'
end
# This is called in lieu of the normal request process
# in the event that OmniAuth has been configured to be
# in test mode.
def mock_call!(*)
begin
return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)
return mock_callback_call if on_callback_path?
rescue StandardError => e
raise e if env.delete('omniauth.error.app')
return fail!(e.message, e)
end
call_app!
end
def mock_request_call
setup_phase
session['omniauth.params'] = request.GET
OmniAuth.config.request_validation_phase.call(env) if OmniAuth.config.request_validation_phase
OmniAuth.config.before_request_phase.call(env) if OmniAuth.config.before_request_phase
if options.origin_param
if request.params[options.origin_param]
session['omniauth.origin'] = request.params[options.origin_param]
elsif env['HTTP_REFERER'] && !env['HTTP_REFERER'].match(/#{request_path}$/)
session['omniauth.origin'] = env['HTTP_REFERER']
end
end
result = redirect(callback_url)
OmniAuth.config.after_request_phase.call(env) if OmniAuth.config.after_request_phase
result
end
def mock_callback_call
setup_phase
origin = session.delete('omniauth.origin')
@env['omniauth.origin'] ||= origin
@env['omniauth.origin'] = nil if env['omniauth.origin'] == ''
@env['omniauth.params'] = session.delete('omniauth.params') || {}
mocked_auth = OmniAuth.mock_auth_for(name.to_s)
if mocked_auth.is_a?(Symbol)
fail!(mocked_auth)
else
@env['omniauth.auth'] = mocked_auth
OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase
call_app!
end
end
# The setup phase looks for the `:setup` option to exist and,
# if it is, will call either the Rack endpoint supplied to the
# `:setup` option or it will call out to the setup path of the
# underlying application. This will default to `/auth/:provider/setup`.
def setup_phase
if options[:setup].respond_to?(:call)
log :debug, 'Setup endpoint detected, running now.'
options[:setup].call(env)
elsif options[:setup]
log :debug, 'Calling through to underlying application for setup.'
setup_env = env.merge('PATH_INFO' => setup_path, 'REQUEST_METHOD' => 'GET')
call_app!(setup_env)
end
end
# @abstract This method is called when the user is on the request path. You should
# perform any information gathering you need to be able to authenticate
# the user in this phase.
def request_phase
raise(NotImplementedError)
end
def uid
self.class.uid_stack(self).last
end
def info
merge_stack(self.class.info_stack(self))
end
def credentials
merge_stack(self.class.credentials_stack(self))
end
def extra
merge_stack(self.class.extra_stack(self))
end
def auth_hash
credentials_data = credentials
extra_data = extra
AuthHash.new(:provider => name, :uid => uid).tap do |auth|
auth.info = info unless skip_info?
auth.credentials = credentials_data if credentials_data
auth.extra = extra_data if extra_data
end
end
# Determines whether or not user info should be retrieved. This
# allows some strategies to save a call to an external API service
# for existing users. You can use it either by setting the `:skip_info`
# to true or by setting `:skip_info` to a Proc that takes a uid and
# evaluates to true when you would like to skip info.
#
# @example
#
# use MyStrategy, :skip_info => lambda{|uid| User.find_by_uid(uid)}
def skip_info?
return false unless options.skip_info?
return true unless options.skip_info.respond_to?(:call)
options.skip_info.call(uid)
end
def callback_phase
env['omniauth.auth'] = auth_hash
call_app!
end
def path_prefix
options[:path_prefix] || OmniAuth.config.path_prefix
end
def custom_path(kind)
if options[kind].respond_to?(:call)
result = options[kind].call(env)
return nil unless result.is_a?(String)
result
else
options[kind]
end
end
def request_path
@request_path ||=
if options[:request_path].is_a?(String)
options[:request_path]
else
"#{script_name}#{path_prefix}/#{name}"
end
end
def callback_path
@callback_path ||= begin
path = options[:callback_path] if options[:callback_path].is_a?(String)
path ||= current_path if options[:callback_path].respond_to?(:call) && options[:callback_path].call(env)
path ||= custom_path(:request_path)
path ||= "#{script_name}#{path_prefix}/#{name}/callback"
path
end
end
def setup_path
options[:setup_path] || "#{path_prefix}/#{name}/setup"
end
CURRENT_PATH_REGEX = %r{/$}.freeze
EMPTY_STRING = ''.freeze
def current_path
@current_path ||= request.path.downcase.sub(CURRENT_PATH_REGEX, EMPTY_STRING)
end
def query_string
request.query_string.empty? ? '' : "?#{request.query_string}"
end
def call_app!(env = @env)
@app.call(env)
rescue StandardError => e
env['omniauth.error.app'] = true
raise e
end
def full_host
case OmniAuth.config.full_host
when String
OmniAuth.config.full_host
when Proc
OmniAuth.config.full_host.call(env)
else
# in Rack 1.3.x, request.url explodes if scheme is nil
if request.scheme && URI.parse(request.url).absolute?
uri = URI.parse(request.url.gsub(/\?.*$/, ''))
uri.path = ''
# sometimes the url is actually showing http inside rails because the
# other layers (like nginx) have handled the ssl termination.
uri.scheme = 'https' if ssl? # rubocop:disable BlockNesting
uri.to_s
else ''
end
end
end
def callback_url
full_host + callback_path + query_string
end
def script_name
return '' if @env.nil?
@env['SCRIPT_NAME'] || ''
end
def session
@env['rack.session']
end
def request
@request ||= Rack::Request.new(@env)
end
def name
options[:name]
end
def redirect(uri)
r = Rack::Response.new
if options[:iframe]
r.write("<script type='text/javascript' charset='utf-8'>top.location.href = '#{uri}';</script>")
else
r.write("Redirecting to #{uri}...")
r.redirect(uri)
end
r.finish
end
def user_info
{}
end
def fail!(message_key, exception = nil)
env['omniauth.error'] = exception
env['omniauth.error.type'] = message_key.to_sym
env['omniauth.error.strategy'] = self
if exception
log :error, "Authentication failure! #{message_key}: #{exception.class}, #{exception.message}"
else
log :error, "Authentication failure! #{message_key} encountered."
end
OmniAuth.config.on_failure.call(env)
end
class Options < OmniAuth::KeyStore; end
protected
def initialize_copy(*args)
super
@options = @options.dup
end
def merge_stack(stack)
stack.inject({}) do |a, e|
a.merge!(e)
a
end
end
def ssl?
request.env['HTTPS'] == 'on' ||
request.env['HTTP_X_FORWARDED_SSL'] == 'on' ||
request.env['HTTP_X_FORWARDED_SCHEME'] == 'https' ||
(request.env['HTTP_X_FORWARDED_PROTO'] && request.env['HTTP_X_FORWARDED_PROTO'].split(',')[0] == 'https') ||
request.env['rack.url_scheme'] == 'https'
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/form.rb | lib/omniauth/form.rb | module OmniAuth
class Form
DEFAULT_CSS = File.read(File.expand_path('../form.css', __FILE__))
attr_accessor :options
def initialize(options = {})
options[:title] ||= 'Authentication Info Required'
options[:header_info] ||= ''
options[:method] ||= 'post'
self.options = options
@html = +'' # unary + string allows it to be mutable if strings are frozen
@with_custom_button = false
@footer = nil
header(options[:title], options[:header_info])
end
def self.build(options = {}, &block)
form = OmniAuth::Form.new(options)
if block.arity > 0
yield form
else
form.instance_eval(&block)
end
form
end
def label_field(text, target)
@html << "\n<label for='#{target}'>#{text}:</label>"
self
end
def input_field(type, name)
@html << "\n<input type='#{type}' id='#{name}' name='#{name}'/>"
self
end
def text_field(label, name)
label_field(label, name)
input_field('text', name)
self
end
def password_field(label, name)
label_field(label, name)
input_field('password', name)
self
end
def button(text)
@with_custom_button = true
@html << "\n<button type='submit'>#{text}</button>"
end
def html(html)
@html << html
end
def fieldset(legend, options = {}, &block)
@html << "\n<fieldset#{" style='#{options[:style]}'" if options[:style]}#{" id='#{options[:id]}'" if options[:id]}>\n <legend>#{legend}</legend>\n"
instance_eval(&block)
@html << "\n</fieldset>"
self
end
def header(title, header_info)
@html << <<-HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>#{title}</title>
#{css}
#{header_info}
</head>
<body>
<h1>#{title}</h1>
<form method='#{options[:method]}' #{"action='#{options[:url]}' " if options[:url]}noValidate='noValidate'>
HTML
self
end
def footer
return self if @footer
@html << "\n<button type='submit'>Connect</button>" unless @with_custom_button
@html << <<-HTML
</form>
</body>
</html>
HTML
@footer = true
self
end
def to_html
footer
@html
end
def to_response
footer
Rack::Response.new(@html, 200, 'content-type' => 'text/html').finish
end
protected
def css
"\n<style type='text/css'>#{OmniAuth.config.form_css}</style>"
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/failure_endpoint.rb | lib/omniauth/failure_endpoint.rb | module OmniAuth
# This simple Rack endpoint that serves as the default
# 'failure' mechanism for OmniAuth. If a strategy fails for
# any reason this endpoint will be invoked. The default behavior
# is to redirect to `/auth/failure` except in the case of
# a development `RACK_ENV`, in which case an exception will
# be raised.
class FailureEndpoint
attr_reader :env
def self.call(env)
new(env).call
end
def initialize(env)
@env = env
end
def call
raise_out! if OmniAuth.config.failure_raise_out_environments.include?(ENV['RACK_ENV'].to_s)
redirect_to_failure
end
def raise_out!
raise(env['omniauth.error'] || OmniAuth::Error.new(env['omniauth.error.type']))
end
def redirect_to_failure
message_key = env['omniauth.error.type']
new_path = "#{env['SCRIPT_NAME']}#{strategy_path_prefix}/failure?message=#{Rack::Utils.escape(message_key)}#{origin_query_param}#{strategy_name_query_param}"
Rack::Response.new(['302 Moved'], 302, 'Location' => new_path).finish
end
def strategy_path_prefix
if env['omniauth.error.strategy']
env['omniauth.error.strategy'].path_prefix
else
OmniAuth.config.path_prefix
end
end
def strategy_name_query_param
return '' unless env['omniauth.error.strategy']
"&strategy=#{env['omniauth.error.strategy'].name}"
end
def origin_query_param
return '' unless env['omniauth.origin']
"&origin=#{Rack::Utils.escape(env['omniauth.origin'])}"
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/auth_hash.rb | lib/omniauth/auth_hash.rb | require 'omniauth/key_store'
module OmniAuth
# The AuthHash is a normalized schema returned by all OmniAuth
# strategies. It maps as much user information as the provider
# is able to provide into the InfoHash (stored as the `'info'`
# key).
class AuthHash < OmniAuth::KeyStore
def self.subkey_class
Hashie::Mash
end
# Tells you if this is considered to be a valid
# OmniAuth AuthHash. The requirements for that
# are that it has a provider name, a uid, and a
# valid info hash. See InfoHash#valid? for
# more details there.
def valid?
uid? && provider? && info? && info.valid?
end
def regular_writer(key, value)
value = InfoHash.new(value) if key.to_s == 'info' && value.is_a?(::Hash) && !value.is_a?(InfoHash)
super
end
class InfoHash < OmniAuth::KeyStore
def self.subkey_class
Hashie::Mash
end
def name
return self[:name] if self[:name]
return "#{first_name} #{last_name}".strip if first_name? || last_name?
return nickname if nickname?
return email if email?
nil
end
def name?
!!name
end
alias valid? name?
def to_hash
hash = super
hash['name'] ||= name
hash
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/key_store.rb | lib/omniauth/key_store.rb | require 'hashie/mash'
module OmniAuth
# Generic helper hash that allows method access on deeply nested keys.
class KeyStore < ::Hashie::Mash
# Disables warnings on Hashie 3.5.0+ for overwritten keys
def self.override_logging
require 'hashie/version'
return unless Gem::Version.new(Hashie::VERSION) >= Gem::Version.new('3.5.0')
if respond_to?(:disable_warnings)
disable_warnings
else
define_method(:log_built_in_message) { |*| }
private :log_built_in_message
end
end
# Disable on loading of the class
override_logging
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/builder.rb | lib/omniauth/builder.rb | module OmniAuth
class Builder < ::Rack::Builder
def on_failure(&block)
OmniAuth.config.on_failure = block
end
def before_options_phase(&block)
OmniAuth.config.before_options_phase = block
end
def before_request_phase(&block)
OmniAuth.config.before_request_phase = block
end
def after_request_phase(&block)
OmniAuth.config.after_request_phase = block
end
def before_callback_phase(&block)
OmniAuth.config.before_callback_phase = block
end
def configure(&block)
OmniAuth.configure(&block)
end
def options(options = false)
return @options ||= {} if options == false
@options = options
end
def provider(klass, *args, **opts, &block)
if klass.is_a?(Class)
middleware = klass
else
begin
middleware = OmniAuth::Strategies.const_get(OmniAuth::Utils.camelize(klass.to_s).to_s, false)
rescue NameError
raise(LoadError.new("Could not find matching strategy for #{klass.inspect}. You may need to install an additional gem (such as omniauth-#{klass})."))
end
end
use middleware, *args, **options.merge(opts), &block
end
def call(env)
to_app.call(env)
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/test/phony_session.rb | lib/omniauth/test/phony_session.rb | module OmniAuth
module Test
class PhonySession
def initialize(app)
@app = app
end
def call(env)
@session ||= (env['rack.session'] || {})
env['rack.session'] = @session
@app.call(env)
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/test/strategy_macros.rb | lib/omniauth/test/strategy_macros.rb | module OmniAuth
module Test
module StrategyMacros
def sets_an_auth_hash
it 'sets an auth hash' do
expect(last_request.env['omniauth.auth']).to be_kind_of(Hash)
end
end
def sets_provider_to(provider)
it "sets the provider to #{provider}" do
expect((last_request.env['omniauth.auth'] || {})['provider']).to eq provider
end
end
def sets_uid_to(uid)
it "sets the UID to #{uid}" do
expect((last_request.env['omniauth.auth'] || {})['uid']).to eq uid
end
end
def sets_user_info_to(user_info)
it "sets the user_info to #{user_info}" do
expect((last_request.env['omniauth.auth'] || {})['user_info']).to eq user_info
end
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/test/strategy_test_case.rb | lib/omniauth/test/strategy_test_case.rb | require 'rack'
require 'omniauth/test'
module OmniAuth
module Test
# Support for testing OmniAuth strategies.
#
# @example Usage
# class MyStrategyTest < Test::Unit::TestCase
# include OmniAuth::Test::StrategyTestCase
# def strategy
# # return the parameters to a Rack::Builder map call:
# [MyStrategy, :some, :configuration, :options => 'here']
# end
# setup do
# post '/auth/my_strategy/callback', :user => { 'name' => 'Dylan', 'id' => '445' }
# end
# end
module StrategyTestCase
def app
strat = strategy
resp = app_response
Rack::Builder.new do
use(OmniAuth::Test::PhonySession)
use(*strat)
run lambda { |env| [404, {'Content-Type' => 'text/plain'}, [resp || env.key?('omniauth.auth').to_s]] }
end.to_app
end
def app_response
nil
end
def session
last_request.env['rack.session']
end
def strategy
error = NotImplementedError.new('Including specs must define #strategy')
raise(error)
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
omniauth/omniauth | https://github.com/omniauth/omniauth/blob/20ac5e05a39d58d18aca6419599f7176208f985d/lib/omniauth/strategies/developer.rb | lib/omniauth/strategies/developer.rb | module OmniAuth
module Strategies
# The Developer strategy is a very simple strategy that can be used as a
# placeholder in your application until a different authentication strategy
# is swapped in. It has zero security and should *never* be used in a
# production setting.
#
# ## Usage
#
# To use the Developer strategy, all you need to do is put it in like any
# other strategy:
#
# @example Basic Usage
#
# use OmniAuth::Builder do
# provider :developer
# end
#
# @example Custom Fields
#
# use OmniAuth::Builder do
# provider :developer,
# :fields => [:first_name, :last_name],
# :uid_field => :last_name
# end
#
# This will create a strategy that, when the user visits `/auth/developer`
# they will be presented a form that prompts for (by default) their name
# and email address. The auth hash will be populated with these fields and
# the `uid` will simply be set to the provided email.
class Developer
include OmniAuth::Strategy
option :fields, %i[name email]
option :uid_field, :email
def request_phase
form = OmniAuth::Form.new(:title => 'User Info', :url => callback_path, :method => 'get')
options.fields.each do |field|
form.text_field field.to_s.capitalize.tr('_', ' '), field.to_s
end
form.button 'Sign In'
form.to_response
end
uid do
request.params[options.uid_field.to_s]
end
info do
options.fields.inject({}) do |hash, field|
hash[field] = request.params[field.to_s]
hash
end
end
end
end
end
| ruby | MIT | 20ac5e05a39d58d18aca6419599f7176208f985d | 2026-01-04T15:39:12.494207Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/github_changelog_generator_spec.rb | spec/github_changelog_generator_spec.rb | # frozen_string_literal: true
RSpec.describe GitHubChangelogGenerator::ChangelogGenerator do
describe "#run" do
let(:arguments) { [] }
let(:instance) { described_class.new(arguments) }
let(:output_path) { File.join(__dir__, "tmp", "test.output") }
after { FileUtils.rm_rf(output_path) }
let(:generator) { instance_double(::GitHubChangelogGenerator::Generator) }
before do
allow(instance).to receive(:generator) { generator }
allow(generator).to receive(:compound_changelog) { "content" }
end
context "when full path given as the --output argument" do
let(:arguments) { ["--output", output_path] }
it "puts the complete output path to STDOUT" do
expect { instance.run }.to output(Regexp.new(output_path)).to_stdout
end
end
context "when empty value given as the --output argument" do
let(:arguments) { ["--output", ""] }
it "puts the complete output path to STDOUT" do
expect { instance.run }.to output(/content/).to_stdout
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
#
# Author:: Enrico Stahn <mail@enricostahn.com>
#
# Copyright 2014, Zanui, <engineering@zanui.com.au>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "simplecov"
require "vcr"
require "webmock/rspec"
# This module is only used to check the environment is currently a testing env
module SpecHelper
end
SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter
SimpleCov.start do
add_filter "gemfiles/"
end
require "github_changelog_generator"
require "github_changelog_generator/task"
VCR.configure do |c|
c.allow_http_connections_when_no_cassette = true
c.cassette_library_dir = "spec/vcr"
c.ignore_localhost = true
c.default_cassette_options = {
record: :new_episodes,
serialize_with: :json,
preserve_exact_body_bytes: true,
decode_compressed_response: true
}
c.filter_sensitive_data("<GITHUB_TOKEN>") do
"token #{ENV.fetch('CHANGELOG_GITHUB_TOKEN', 'frobnitz')}"
end
c.configure_rspec_metadata!
c.hook_into :webmock, :faraday
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.warnings = true
config.default_formatter = "doc" if config.files_to_run.one?
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/reader_spec.rb | spec/unit/reader_spec.rb | # frozen_string_literal: true
#
# Author:: Enrico Stahn <mail@enricostahn.com>
#
# Copyright 2014, Zanui, <engineering@zanui.com.au>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
describe GitHubChangelogGenerator::Reader do
before(:all) do
@reader = GitHubChangelogGenerator::Reader.new
end
describe "#parse_heading" do
context "when heading is empty" do
subject { @reader.parse_heading("## ") }
it { is_expected.to be_a(Hash) }
it { is_expected.to include("version", "url", "date") }
it { is_expected.to include("version" => nil, "url" => nil, "date" => nil) }
# TODO: Doesn't work?
# it { is_expected.to have_all_string_keys }
end
context "when given version, url and date" do
subject { @reader.parse_heading("## [1.3.10](https://github.com/github-changelog-generator/Github-Changelog-Generator/tree/1.3.10) (2015-03-18)") }
it { is_expected.to include("version" => "1.3.10") }
it { is_expected.to include("url" => "https://github.com/github-changelog-generator/Github-Changelog-Generator/tree/1.3.10") }
it { is_expected.to include("date" => "2015-03-18") }
end
context "when given a named link" do
subject { @reader.parse_heading("## [1.3.10]") }
it { is_expected.to include("version" => "1.3.10") }
end
context "when given a named link with date" do
subject { @reader.parse_heading("## [1.3.10] (2015-03-18)") }
it { is_expected.to include("version" => "1.3.10") }
it { is_expected.to include("date" => "2015-03-18") }
end
context "when no url and date is provided" do
subject { @reader.parse_heading("## foobar") }
it { is_expected.to include("version" => "foobar", "url" => nil, "date" => nil) }
end
end
describe "#parse" do
context "when file is empty" do
subject { @reader.parse("") }
it { is_expected.to be_an(Array) }
it { is_expected.to be_empty }
end
context "when file has only the header" do
subject { @reader.parse("# Changelog") }
it { is_expected.to be_an(Array) }
it { is_expected.to be_empty }
end
end
describe "example CHANGELOG files" do
subject { @reader.read(File.expand_path(File.join(File.dirname(__FILE__), "..", "files", self.class.description))) }
context "github-changelog-generator.md" do
it { is_expected.to be_an(Array) }
it { is_expected.not_to be_empty }
it { expect(subject.count).to eq(28) }
it { expect(subject.first).to include("version" => "1.3.10") }
it { expect(subject.first).to include("url" => "https://github.com/github-changelog-generator/Github-Changelog-Generator/tree/1.3.10") }
it { expect(subject.first).to include("date" => "2015-03-18") }
it { expect(subject.first).to include("content") }
it "content should not be empty" do
expect(subject.first["content"]).not_to be_empty
end
end
context "bundler.md" do
it { is_expected.to be_an(Array) }
it { is_expected.not_to be_empty }
it { expect(subject.count).to eq(151) }
it { expect(subject.first).to include("version" => "1.9.1") }
it { expect(subject.first).to include("url" => nil) }
it { expect(subject.first).to include("date" => "2015-03-21") }
it { expect(subject.first).to include("content") }
it "content should not be empty" do
expect(subject.first["content"]).not_to be_empty
end
end
context "angular.js.md" do
it { is_expected.to be_an(Array) }
it { is_expected.not_to be_empty }
# it do
# pending('Implement heading_level for parser.')
# expect(subject.first).to include('version' => '1.4.0-beta.6 cookie-liberation')
# end
# it do
# pending('Implement heading_level for parser.')
# expect(subject.first).to include('url' => nil)
# end
# it do
# pending('Implement heading_level for parser.')
# expect(subject.first).to include('date' => '2015-03-17')
# end
# it do
# pending('Implement heading_level for parser.')
# expect(subject.first).to include('content')
# end
# it 'content should not be empty' do
# pending('Implement heading_level for parser.')
# expect(subject.first['content']).not_to be_empty
# end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/parser_spec.rb | spec/unit/parser_spec.rb | # frozen_string_literal: true
describe GitHubChangelogGenerator::Parser do
let(:argv) { [] }
before do
# Calling abort will abort the test run, allow calls to abort to not accidentaly get positive falses
allow(Kernel).to receive(:abort)
end
describe ".parse_options" do
context "when required arguments are given" do
let(:argv) { ["--user", "the user", "--project", "the_project"] }
it "executes and prints the configuration" do
expect { described_class.parse_options(argv) }.to output(/config_file=>".github_changelog_generator"/).to_stdout
end
end
context "when --config-file is overridden to something that is not there" do
let(:argv) { ["--config-file", "does_not_exist"] }
it "aborts the execution" do
expect(Kernel).to receive(:abort)
expect { described_class.parse_options(argv) }.to output(/Configure which user and project to work on./).to_stderr
end
end
context "when an option with incorrect type is given" do
let(:argv) { ["--max-issues", "X"] }
it "aborts the execution with error message from parser" do
expect(Kernel).to receive(:abort)
expect { described_class.parse_options(argv) }.to output(/invalid argument: --max-issues X/).to_stderr
end
end
context "when path to configuration file is given" do
let(:argv) { ["--config-file", File.join(__dir__, "..", "files", "config_example")] }
it "uses the values from the configuration file" do
expect { described_class.parse_options(argv) }.to output(/spec_project/).to_stdout
end
end
context "when configuration file and parameters are given" do
let(:argv) { ["--project", "stronger_project", "--config-file", File.join(__dir__, "..", "files", "config_example")] }
it "uses the values from the arguments" do
expect { described_class.parse_options(argv) }.to output(/stronger_project/).to_stdout
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/parser_file_spec.rb | spec/unit/parser_file_spec.rb | # frozen_string_literal: true
describe GitHubChangelogGenerator::ParserFile do
describe ".github_changelog_generator" do
let(:options) { {} }
let(:parser) { described_class.new(options, StringIO.new(file)) }
context "when the well-known default file does not exist" do
let(:parser) { described_class.new(options) }
subject { parser.parse! }
it { is_expected.to be_nil }
end
context "when file is empty" do
let(:file) { "" }
it "does not change the options" do
expect { parser.parse! }.to_not(change { options })
end
end
context "when file is incorrect" do
let(:file) do
<<~FILE.strip
unreleased_label=staging
unreleased: false
FILE
end
it { expect { parser.parse! }.to raise_error(/line #2/) }
end
context "allows empty lines and comments with semi-colon or pound sign" do
let(:file) do
"\n \n#{<<~REMAINING.strip}"
# Comment on first line
unreleased_label=staging
; Comment on third line
unreleased=false
REMAINING
end
it { expect { parser.parse! }.not_to raise_error }
end
context "when override default values" do
let(:default_options) { GitHubChangelogGenerator::Parser.default_options.merge(verbose: false) }
let(:options) { {}.merge(default_options) }
let(:options_before_change) { options.dup }
let(:file) do
<<~FILE.strip
unreleased_label=staging
unreleased=false
header==== Changelog ===
max_issues=123
simple-list=true
FILE
end
it "changes the options" do
expect { parser.parse! }.to change { options }
.from(options_before_change)
.to(options_before_change.merge(unreleased_label: "staging",
unreleased: false,
header: "=== Changelog ===",
max_issues: 123,
simple_list: true))
end
context "turns exclude-labels into an Array", bug: "#327" do
let(:file) do
<<~FILE
exclude-labels=73a91042-da6f-11e5-9335-1040f38d7f90,7adf83b4-da6f-11e5-ae18-1040f38d7f90
header_label=# My changelog
FILE
end
it "reads exclude_labels into an Array" do
expect { parser.parse! }.to change { options[:exclude_labels] }
.from(default_options[:exclude_labels])
.to(%w[73a91042-da6f-11e5-9335-1040f38d7f90 7adf83b4-da6f-11e5-ae18-1040f38d7f90])
end
it "translates given header_label into the :header option" do
expect { parser.parse! }.to change { options[:header] }
.from(default_options[:header])
.to("# My changelog")
end
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/octo_fetcher_spec.rb | spec/unit/octo_fetcher_spec.rb | # frozen_string_literal: true
VALID_TOKEN = "0123456789abcdef"
INVALID_TOKEN = "0000000000000000"
describe GitHubChangelogGenerator::OctoFetcher do
let(:options) do
{
user: "github-changelog-generator",
project: "changelog_test"
}
end
let(:fetcher) { GitHubChangelogGenerator::OctoFetcher.new(options) }
describe "#check_github_response" do
context "when returns successfully" do
it "returns block value" do
expect(fetcher.send(:check_github_response) { 1 + 1 }).to eq(2)
end
end
context "when raises Octokit::Unauthorized" do
it "aborts" do
expect(fetcher).to receive(:sys_abort).with("Error: wrong GitHub token")
fetcher.send(:check_github_response) { raise(Octokit::Unauthorized) }
end
end
context "when raises Octokit::Forbidden" do
it "sleeps and retries and then aborts" do
expect(fetcher).to receive(:sys_abort).with("Exceeded retry limit")
fetcher.send(:check_github_response) { raise(Octokit::Forbidden) }
end
end
end
describe "#fetch_github_token" do
token = GitHubChangelogGenerator::OctoFetcher::CHANGELOG_GITHUB_TOKEN
context "when token in ENV exist" do
before { stub_const("ENV", ENV.to_hash.merge(token => VALID_TOKEN)) }
subject { fetcher.send(:fetch_github_token) }
it { is_expected.to eq(VALID_TOKEN) }
end
context "when token in ENV is nil" do
before { stub_const("ENV", ENV.to_hash.merge(token => nil)) }
subject { fetcher.send(:fetch_github_token) }
it { is_expected.to be_nil }
end
context "when token in options and ENV is nil" do
let(:options) { { token: VALID_TOKEN } }
before do
stub_const("ENV", ENV.to_hash.merge(token => nil))
end
subject { fetcher.send(:fetch_github_token) }
it { is_expected.to eq(VALID_TOKEN) }
end
context "when token in options and ENV specified" do
let(:options) { { token: VALID_TOKEN } }
before do
stub_const("ENV", ENV.to_hash.merge(token => "no_matter_what"))
end
subject { fetcher.send(:fetch_github_token) }
it { is_expected.to eq(VALID_TOKEN) }
end
end
describe "#fetch_all_tags" do
context "when github_fetch_tags returns tags" do
it "returns tags" do
mock_tags = ["tag"]
allow(fetcher).to receive(:github_fetch_tags).and_return(mock_tags)
expect(fetcher.fetch_all_tags).to eq(mock_tags)
end
end
end
describe "#fetch_tag_shas" do
let(:commits) do
[
{ sha: "0", parents: [{ sha: "1" }, { sha: "6" }] },
{ sha: "1", parents: [{ sha: "2" }] },
{ sha: "2", parents: [{ sha: "3" }] },
{ sha: "3", parents: [{ sha: "4" }] },
{ sha: "4", parents: [{ sha: "5" }] },
{ sha: "5", parents: [] },
{ sha: "6", parents: [{ sha: "7" }, { sha: "8" }] },
{ sha: "7", parents: [{ sha: "9" }, { sha: "10" }] },
{ sha: "8", parents: [{ sha: "11" }, { sha: "12" }] },
{ sha: "9", parents: [] },
{ sha: "10", parents: [] },
{ sha: "11", parents: [] },
{ sha: "12", parents: [] }
]
end
let(:tag0) { { "name" => "tag-0", "commit" => { "sha" => "0" } } }
let(:tag1) { { "name" => "tag-1", "commit" => { "sha" => "1" } } }
let(:tag6) { { "name" => "tag-6", "commit" => { "sha" => "6" } } }
before do
allow(fetcher).to receive(:commits).and_return(commits)
end
it "should find all shas with single parents" do
fetcher.fetch_tag_shas([tag1])
expect(tag1["shas_in_tag"]).to eq(Set.new(%w[1 2 3 4 5]))
end
it "should find all shas with multiple parents" do
fetcher.fetch_tag_shas([tag6])
expect(tag6["shas_in_tag"]).to eq(Set.new(%w[6 7 8 9 10 11 12]))
end
it "should find all shas with mixed parents" do
fetcher.fetch_tag_shas([tag0])
expect(tag0["shas_in_tag"]).to eq(Set.new(%w[0 1 2 3 4 5 6 7 8 9 10 11 12]))
end
end
describe "#github_fetch_tags" do
context "when wrong token provided", :vcr do
let(:options) do
{
user: "github-changelog-generator",
project: "changelog_test",
token: INVALID_TOKEN
}
end
it "should raise Unauthorized error" do
expect { fetcher.github_fetch_tags }.to raise_error SystemExit, "Error: wrong GitHub token"
end
end
context "when API call is valid", :vcr do
it "should return tags" do
expected_tags = [{ "name" => "v0.0.3",
"zipball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/zipball/v0.0.3",
"tarball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/tarball/v0.0.3",
"commit" =>
{ "sha" => "a0cba2b1a1ea9011ab07ee1ac140ba5a5eb8bd90",
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/a0cba2b1a1ea9011ab07ee1ac140ba5a5eb8bd90" } },
{ "name" => "v0.0.2",
"zipball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/zipball/v0.0.2",
"tarball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/tarball/v0.0.2",
"commit" =>
{ "sha" => "9b35bb13dcd15b68e7bcbf10cde5eb937a54f710",
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/9b35bb13dcd15b68e7bcbf10cde5eb937a54f710" } },
{ "name" => "v0.0.1",
"zipball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/zipball/v0.0.1",
"tarball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/tarball/v0.0.1",
"commit" =>
{ "sha" => "4c2d6d1ed58bdb24b870dcb5d9f2ceed0283d69d",
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/4c2d6d1ed58bdb24b870dcb5d9f2ceed0283d69d" } },
{ "name" => "0.0.4",
"zipball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/zipball/0.0.4",
"tarball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/tarball/0.0.4",
"commit" =>
{ "sha" => "ece0c3ab7142b21064b885061c55ede00ef6ce94",
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/ece0c3ab7142b21064b885061c55ede00ef6ce94" } }]
expect(fetcher.github_fetch_tags).to eq(expected_tags)
end
it "should return tags count" do
tags = fetcher.github_fetch_tags
expect(tags.size).to eq(4)
end
end
end
describe "#fetch_closed_issues_and_pr" do
context "when API call is valid", :vcr do
it "returns issues" do
issues, pull_requests = fetcher.fetch_closed_issues_and_pr
expect(issues.size).to eq(7)
expect(pull_requests.size).to eq(14)
end
it "returns issue with proper key/values" do
issues, _pull_requests = fetcher.fetch_closed_issues_and_pr
expected_issue = { "url" => "https://api.github.com/repos/skywinder/changelog_test/issues/14",
"repository_url" => "https://api.github.com/repos/skywinder/changelog_test",
"labels_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/labels{/name}",
"comments_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/comments",
"events_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/events",
"html_url" => "https://github.com/skywinder/changelog_test/issues/14",
"id" => 95_419_412,
"number" => 14,
"title" => "Issue closed from commit from PR",
"user" =>
{ "login" => "skywinder",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" => "https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"labels" => [],
"state" => "closed",
"locked" => false,
"assignee" => nil,
"assignees" => [],
"milestone" => nil,
"comments" => 0,
"created_at" => "2015-07-16T12:06:08Z",
"updated_at" => "2015-07-16T12:21:42Z",
"closed_at" => "2015-07-16T12:21:42Z",
"body" => "" }
# Convert times to Time
expected_issue.each_pair do |k, v|
expected_issue[k] = Time.parse(v) if v.to_s.start_with?("2015-")
end
expect(issues.first).to eq(expected_issue)
end
it "returns pull request with proper key/values" do
_issues, pull_requests = fetcher.fetch_closed_issues_and_pr
expected_pr = { "url" => "https://api.github.com/repos/skywinder/changelog_test/issues/21",
"repository_url" => "https://api.github.com/repos/skywinder/changelog_test",
"labels_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/21/labels{/name}",
"comments_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/21/comments",
"events_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/21/events",
"html_url" => "https://github.com/skywinder/changelog_test/pull/21",
"id" => 124_925_759,
"number" => 21,
"title" => "Merged br (should appear in change log with #20)",
"user" =>
{ "login" => "skywinder",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" => "https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"labels" => [],
"state" => "closed",
"locked" => false,
"assignee" => nil,
"assignees" => [],
"milestone" => nil,
"comments" => 0,
"created_at" => "2016-01-05T09:24:08Z",
"updated_at" => "2016-01-05T09:26:53Z",
"closed_at" => "2016-01-05T09:24:27Z",
"pull_request" =>
{ "url" => "https://api.github.com/repos/skywinder/changelog_test/pulls/21",
"html_url" => "https://github.com/skywinder/changelog_test/pull/21",
"diff_url" => "https://github.com/skywinder/changelog_test/pull/21.diff",
"patch_url" => "https://github.com/skywinder/changelog_test/pull/21.patch" },
"body" =>
"to test https://github.com/skywinder/github-changelog-generator/pull/305\r\nshould appear in change log with #20" }
# Convert times to Time
expected_pr.each_pair do |k, v|
expected_pr[k] = Time.parse(v) if v.to_s.start_with?("2016-01")
end
expect(pull_requests.first).to eq(expected_pr)
end
it "returns issues with labels" do
issues, _pull_requests = fetcher.fetch_closed_issues_and_pr
expected = [[], [], ["Bug"], [], ["enhancement"], ["some label"], []]
expect(issues.map { |i| i["labels"].map { |l| l["name"] } }).to eq(expected)
end
it "returns pull_requests with labels" do
_issues, pull_requests = fetcher.fetch_closed_issues_and_pr
expected = [[], [], [], [], [], ["enhancement"], [], [], ["invalid"], [], [], [], [], ["invalid"]]
expect(pull_requests.map { |i| i["labels"].map { |l| l["name"] } }).to eq(expected)
end
end
end
describe "#fetch_closed_pull_requests" do
context "when API call is valid", :vcr do
it "returns pull requests" do
pull_requests = fetcher.fetch_closed_pull_requests
expect(pull_requests.size).to eq(14)
end
it "returns correct pull request keys" do
pull_requests = fetcher.fetch_closed_pull_requests
pr = pull_requests.first
expect(pr.keys).to eq(%w[url id html_url diff_url patch_url issue_url number state locked title user body created_at updated_at closed_at merged_at merge_commit_sha assignee assignees milestone commits_url review_comments_url review_comment_url comments_url statuses_url head base _links])
end
end
end
describe "#fetch_events_async" do
context "when API call is valid", :vcr do
it "populates issues" do
issues = [{ "url" => "https://api.github.com/repos/skywinder/changelog_test/issues/14",
"repository_url" => "https://api.github.com/repos/skywinder/changelog_test",
"labels_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/labels{/name}",
"comments_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/comments",
"events_url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/14/events",
"html_url" => "https://github.com/skywinder/changelog_test/issues/14",
"id" => 95_419_412,
"number" => 14,
"title" => "Issue closed from commit from PR",
"user" =>
{ "login" => "skywinder",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" =>
"https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"labels" => [],
"state" => "closed",
"locked" => false,
"assignee" => nil,
"assignees" => [],
"milestone" => nil,
"comments" => 0,
"created_at" => "2015-07-16T12:06:08Z",
"updated_at" => "2015-07-16T12:21:42Z",
"closed_at" => "2015-07-16T12:21:42Z",
"body" => "" }]
# Check that they are blank to begin with
expect(issues.first["events"]).to be_nil
fetcher.fetch_events_async(issues)
issue_events = issues.first["events"]
expected_events = [{ "id" => 357_462_189,
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/events/357462189",
"actor" =>
{ "login" => "skywinder",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" =>
"https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"event" => "referenced",
"commit_id" => "decfe840d1a1b86e0c28700de5362d3365a29555",
"commit_url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/decfe840d1a1b86e0c28700de5362d3365a29555",
"created_at" => "2015-07-16T12:21:16Z" },
{ "id" => 357_462_542,
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/events/357462542",
"actor" =>
{ "login" => "skywinder",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" =>
"https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"event" => "closed",
"commit_id" => "decfe840d1a1b86e0c28700de5362d3365a29555",
"commit_url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/decfe840d1a1b86e0c28700de5362d3365a29555",
"created_at" => "2015-07-16T12:21:42Z" }]
# Convert times to Time
expected_events.map! do |event|
event.each_pair do |k, v|
event[k] = Time.parse(v) if v.to_s =~ /^201[56]-/
end
end
expect(issue_events).to eq(expected_events)
end
end
end
describe "#fetch_date_of_tag" do
context "when API call is valid", :vcr do
it "returns date" do
tag = { "name" => "v0.0.3",
"zipball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/zipball/v0.0.3",
"tarball_url" =>
"https://api.github.com/repos/skywinder/changelog_test/tarball/v0.0.3",
"commit" =>
{ "sha" => "a0cba2b1a1ea9011ab07ee1ac140ba5a5eb8bd90",
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/a0cba2b1a1ea9011ab07ee1ac140ba5a5eb8bd90" } }
skywinder = GitHubChangelogGenerator::OctoFetcher.new(
user: "skywinder",
project: "changelog_test"
)
dt = skywinder.fetch_date_of_tag(tag)
expect(dt).to eq(Time.parse("2015-03-04 19:01:48 UTC"))
end
end
end
describe "#querystring_as_hash" do
it "works on the blank URL" do
expect { fetcher.send(:querystring_as_hash, "") }.not_to raise_error
end
it "where there are no querystring params" do
expect { fetcher.send(:querystring_as_hash, "http://example.com") }.not_to raise_error
end
it "returns a String-keyed Hash of querystring params" do
expect(fetcher.send(:querystring_as_hash, "http://example.com/o.html?str=18&wis=12")).to include("wis" => "12", "str" => "18")
end
end
describe "#fetch_commit" do
context "when API call is valid", :vcr do
it "returns commit" do
event = { "id" => 357_462_189,
"url" =>
"https://api.github.com/repos/skywinder/changelog_test/issues/events/357462189",
"actor" =>
{ "login" => "github-changelog-generator",
"id" => 3_356_474,
"avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=3",
"gravatar_id" => "",
"url" => "https://api.github.com/users/skywinder",
"html_url" => "https://github.com/skywinder",
"followers_url" => "https://api.github.com/users/skywinder/followers",
"following_url" =>
"https://api.github.com/users/skywinder/following{/other_user}",
"gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}",
"starred_url" =>
"https://api.github.com/users/skywinder/starred{/owner}{/repo}",
"subscriptions_url" => "https://api.github.com/users/skywinder/subscriptions",
"organizations_url" => "https://api.github.com/users/skywinder/orgs",
"repos_url" => "https://api.github.com/users/skywinder/repos",
"events_url" => "https://api.github.com/users/skywinder/events{/privacy}",
"received_events_url" =>
"https://api.github.com/users/skywinder/received_events",
"type" => "User",
"site_admin" => false },
"event" => "referenced",
"commit_id" => "decfe840d1a1b86e0c28700de5362d3365a29555",
"commit_url" =>
"https://api.github.com/repos/skywinder/changelog_test/commits/decfe840d1a1b86e0c28700de5362d3365a29555",
"created_at" => "2015-07-16T12:21:16Z" }
commit = fetcher.fetch_commit(event["commit_id"])
expectations = [
%w[sha decfe840d1a1b86e0c28700de5362d3365a29555],
["url",
"https://api.github.com/repos/github-changelog-generator/changelog_test/commits/decfe840d1a1b86e0c28700de5362d3365a29555"],
# OLD API: "https://api.github.com/repos/skywinder/changelog_test/git/commits/decfe840d1a1b86e0c28700de5362d3365a29555"],
["html_url",
"https://github.com/github-changelog-generator/changelog_test/commit/decfe840d1a1b86e0c28700de5362d3365a29555"],
["author",
{ "login" => "skywinder", "node_id" => "MDQ6VXNlcjMzNTY0NzQ=", "id" => 3_356_474, "avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=4", "gravatar_id" => "", "url" => "https://api.github.com/users/skywinder", "html_url" => "https://github.com/skywinder", "followers_url" => "https://api.github.com/users/skywinder/followers", "following_url" => "https://api.github.com/users/skywinder/following{/other_user}", "gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}", "starred_url" => "https://api.github.com/users/skywinder/starred{/owner}{/repo}", "subscriptions_url" => "https://api.github.com/users/skywinder/subscriptions", "organizations_url" => "https://api.github.com/users/skywinder/orgs", "repos_url" => "https://api.github.com/users/skywinder/repos", "events_url" => "https://api.github.com/users/skywinder/events{/privacy}", "received_events_url" => "https://api.github.com/users/skywinder/received_events", "type" => "User", "site_admin" => false }],
["committer",
{ "login" => "skywinder", "node_id" => "MDQ6VXNlcjMzNTY0NzQ=", "id" => 3_356_474, "avatar_url" => "https://avatars.githubusercontent.com/u/3356474?v=4", "gravatar_id" => "", "url" => "https://api.github.com/users/skywinder", "html_url" => "https://github.com/skywinder", "followers_url" => "https://api.github.com/users/skywinder/followers", "following_url" => "https://api.github.com/users/skywinder/following{/other_user}", "gists_url" => "https://api.github.com/users/skywinder/gists{/gist_id}", "starred_url" => "https://api.github.com/users/skywinder/starred{/owner}{/repo}", "subscriptions_url" => "https://api.github.com/users/skywinder/subscriptions", "organizations_url" => "https://api.github.com/users/skywinder/orgs", "repos_url" => "https://api.github.com/users/skywinder/repos", "events_url" => "https://api.github.com/users/skywinder/events{/privacy}", "received_events_url" => "https://api.github.com/users/skywinder/received_events", "type" => "User", "site_admin" => false }],
["parents",
[{ "sha" => "7ec095e5e3caceacedabf44d0b9b10da17c92e51",
"url" =>
"https://api.github.com/repos/github-changelog-generator/changelog_test/commits/7ec095e5e3caceacedabf44d0b9b10da17c92e51",
# OLD API: "https://api.github.com/repos/skywinder/changelog_test/git/commits/7ec095e5e3caceacedabf44d0b9b10da17c92e51",
"html_url" =>
"https://github.com/github-changelog-generator/changelog_test/commit/7ec095e5e3caceacedabf44d0b9b10da17c92e51" }]]
]
expectations.each do |property, value|
case value
when String, Array
expect(commit[property]).to eq(value)
when Hash
expect(commit[property]).to include(value)
end
end
end
end
end
describe "#commits" do
context "when API is valid", :vcr do
subject do
fetcher.commits
end
it "returns commits" do
expect(subject.last["sha"]).to eq("4c2d6d1ed58bdb24b870dcb5d9f2ceed0283d69d")
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/options_spec.rb | spec/unit/options_spec.rb | # frozen_string_literal: true
RSpec.describe GitHubChangelogGenerator::Options do
describe "#initialize" do
context "with known options" do
it "instantiates successfully" do
expect(described_class.new(user: "olle")[:user]).to eq("olle")
end
end
context "with unknown options" do
it "raises an error" do
expect do
described_class.new(
project: "rails",
strength: "super-strength",
wisdom: "deep"
)
end.to raise_error("[:strength, :wisdom]")
end
end
end
describe "#[]=(key, value)" do
let(:options) { described_class.new(project: "rails") }
context "with known options" do
it "sets the option value" do
expect do
options[:project] = "trails"
end.to change { options[:project] }.to "trails"
end
end
context "with unknown options" do
it "raises an error" do
expect do
options[:charisma] = 8
end.to raise_error(":charisma")
end
end
end
describe "#write_to_file?" do
subject { options.write_to_file? }
let(:options) { described_class.new(output: output) }
context "with filename" do
let(:output) { "CHANGELOG.md" }
it { is_expected.to eq true }
end
context "with nil" do
let(:output) { nil }
it { is_expected.to eq false }
end
context "with empty string" do
let(:output) { "" }
it { is_expected.to eq false }
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/generator/entry_spec.rb | spec/unit/generator/entry_spec.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
RSpec.describe Entry do
def label(name)
{ "name" => name }
end
def issue(title, labels, body = "", number = "1", user = { "login" => "user" })
{
"title" => "issue #{title}",
"labels" => labels.map { |l| label(l) },
"number" => number,
"html_url" => "https://github.com/owner/repo/issue/#{number}",
"user" => user,
"body" => body,
"events" => [{
"event" => "closed"
}]
}
end
def pr(title, labels, body = "", number = "1", user = { "login" => "user" })
{
"pull_request" => true,
"title" => "pr #{title}",
"labels" => labels.map { |l| label(l) },
"number" => number,
"html_url" => "https://github.com/owner/repo/pull/#{number}",
"user" => user.merge("html_url" => "https://github.com/#{user['login']}"),
"body" => body,
"merged_at" => Time.now.utc,
"events" => [{
"event" => "merged",
"commit_id" => "aaaaa#{number}"
}]
}
end
def tag(name, sha, shas_in_tag)
{
"name" => name,
"commit" => { "sha" => sha },
"shas_in_tag" => shas_in_tag
}
end
def titles_for(issues)
issues.map { |issue| issue["title"] }
end
def default_sections
%w[breaking enhancements bugs deprecated removed security issues]
end
# Default to no issues, PRs, or tags.
let(:issues) { [] }
let(:pull_requests) { [] }
let(:tags) { [] }
# Default to standard options minus verbose to avoid output during testing.
let(:options) do
Parser.default_options.merge(verbose: false)
end
# Mock out fake github fetching for the issues/pull_requests lets and then
# expose filtering from the GitHubChangelogGenerator::Generator class
# instance for end-to-end entry testing.
let(:generator) do
fake_fetcher = instance_double(
"fetcher",
fetch_closed_issues_and_pr: [issues, pull_requests],
fetch_closed_pull_requests: [],
fetch_events_async: issues + pull_requests,
fetch_tag_shas: nil,
fetch_comments_async: nil,
default_branch: "master",
oldest_commit: { "sha" => "aaaaa1" },
fetch_commit: { "commit" => { "author" => { "date" => Time.now.utc } } }
)
allow(fake_fetcher).to receive(:commits_in_branch) do
["aaaaa1"]
end
allow(GitHubChangelogGenerator::OctoFetcher).to receive(:new).and_return(fake_fetcher)
generator = GitHubChangelogGenerator::Generator.new(options)
generator.instance_variable_set :@sorted_tags, tags
generator.send(:fetch_issues_and_pr)
generator
end
let(:filtered_issues) do
generator.instance_variable_get :@issues
end
let(:filtered_pull_requests) do
generator.instance_variable_get :@pull_requests
end
let(:entry_sections) do
subject.send(:create_sections)
# In normal usage, the entry generation would have received filtered
# issues and pull requests so replicate that here for ease of testing.
subject.send(:sort_into_sections, filtered_pull_requests, filtered_issues)
subject.instance_variable_get :@sections
end
describe "#generate_entry_for_tag" do
let(:issues) do
[
issue("no labels", [], "", "5", "login" => "user1"),
issue("breaking", ["breaking"], "", "8", "login" => "user5"),
issue("enhancement", ["enhancement"], "", "6", "login" => "user2"),
issue("bug", ["bug"], "", "7", "login" => "user1"),
issue("deprecated", ["deprecated"], "", "13", "login" => "user5"),
issue("removed", ["removed"], "", "14", "login" => "user2"),
issue("security", ["security"], "", "15", "login" => "user5"),
issue("all the labels", %w[breaking enhancement bug deprecated removed security], "", "9", "login" => "user9"),
issue("all the labels different order", %w[bug breaking enhancement security removed deprecated], "", "10", "login" => "user5"),
issue("some unmapped labels", %w[tests-fail bug], "", "11", "login" => "user5"),
issue("no mapped labels", %w[docs maintenance], "", "12", "login" => "user5")
]
end
let(:pull_requests) do
[
pr("no labels", [], "", "20", "login" => "user1"),
pr("breaking", ["breaking"], "", "23", "login" => "user5"),
pr("enhancement", ["enhancement"], "", "21", "login" => "user5"),
pr("bug", ["bug"], "", "22", "login" => "user5"),
pr("deprecated", ["deprecated"], "", "28", "login" => "user5"),
pr("removed", ["removed"], "", "29", "login" => "user2"),
pr("security", ["security"], "", "30", "login" => "user5"),
pr("all the labels", %w[breaking enhancement bug deprecated removed security], "", "24", "login" => "user5"),
pr("all the labels different order", %w[bug breaking enhancement security remove deprecated], "", "25", "login" => "user5"),
pr("some unmapped labels", %w[tests-fail bug], "", "26", "login" => "user5"),
pr("no mapped labels", %w[docs maintenance], "", "27", "login" => "user5")
]
end
let(:tags) do
[tag("1.0.0", "aaaaa30", (1..30).collect { |i| "aaaaa#{i}" })]
end
subject { described_class.new(options) }
describe "include issues without labels" do
let(:options) do
Parser.default_options.merge(
user: "owner",
project: "repo",
breaking_labels: ["breaking"],
enhancement_labels: ["enhancement"],
bug_labels: ["bug"],
deprecated_labels: ["deprecated"],
removed_labels: ["removed"],
security_labels: ["security"],
verbose: false
)
end
it "generates a header and body" do
changelog = <<-CHANGELOG.gsub(/^ {10}/, "")
## [1.0.1](https://github.com/owner/repo/tree/1.0.1) (2017-12-04)
[Full Changelog](https://github.com/owner/repo/compare/1.0.0...1.0.1)
**Breaking changes:**
- issue breaking [\\#8](https://github.com/owner/repo/issue/8)
- issue all the labels [\\#9](https://github.com/owner/repo/issue/9)
- issue all the labels different order [\\#10](https://github.com/owner/repo/issue/10)
- pr breaking [\\#23](https://github.com/owner/repo/pull/23) ([user5](https://github.com/user5))
- pr all the labels [\\#24](https://github.com/owner/repo/pull/24) ([user5](https://github.com/user5))
- pr all the labels different order [\\#25](https://github.com/owner/repo/pull/25) ([user5](https://github.com/user5))
**Implemented enhancements:**
- issue enhancement [\\#6](https://github.com/owner/repo/issue/6)
- pr enhancement [\\#21](https://github.com/owner/repo/pull/21) ([user5](https://github.com/user5))
**Fixed bugs:**
- issue bug [\\#7](https://github.com/owner/repo/issue/7)
- issue some unmapped labels [\\#11](https://github.com/owner/repo/issue/11)
- pr bug [\\#22](https://github.com/owner/repo/pull/22) ([user5](https://github.com/user5))
- pr some unmapped labels [\\#26](https://github.com/owner/repo/pull/26) ([user5](https://github.com/user5))
**Deprecated:**
- issue deprecated [\\#13](https://github.com/owner/repo/issue/13)
- pr deprecated [\\#28](https://github.com/owner/repo/pull/28) ([user5](https://github.com/user5))
**Removed:**
- issue removed [\\#14](https://github.com/owner/repo/issue/14)
- pr removed [\\#29](https://github.com/owner/repo/pull/29) ([user2](https://github.com/user2))
**Security fixes:**
- issue security [\\#15](https://github.com/owner/repo/issue/15)
- pr security [\\#30](https://github.com/owner/repo/pull/30) ([user5](https://github.com/user5))
**Closed issues:**
- issue no labels [\\#5](https://github.com/owner/repo/issue/5)
- issue no mapped labels [\\#12](https://github.com/owner/repo/issue/12)
**Merged pull requests:**
- pr no labels [\\#20](https://github.com/owner/repo/pull/20) ([user1](https://github.com/user1))
- pr no mapped labels [\\#27](https://github.com/owner/repo/pull/27) ([user5](https://github.com/user5))
CHANGELOG
expect(subject.generate_entry_for_tag(pull_requests, issues, "1.0.1", "1.0.1", Time.new(2017, 12, 4, 12, 0, 0, "+00:00").utc, "1.0.0")).to eq(changelog)
end
end
describe "#create_entry_for_tag_with_body" do
let(:options) do
Parser.default_options.merge(
user: "owner",
project: "repo",
bug_labels: ["bug"],
enhancement_labels: ["enhancement"],
breaking_labels: ["breaking"],
issue_line_body: true
)
end
let(:issues_with_body) do
[
issue("no labels", [], "Issue body description", "5", "login" => "user1"),
issue("breaking", ["breaking"], "Issue body description very long: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.", "8", "login" => "user5"),
issue("enhancement", ["enhancement"], "Issue body description", "6", "login" => "user2"),
issue("bug", ["bug"], "Issue body description", "7", "login" => "user1"),
issue("deprecated", ["deprecated"], "Issue body description", "13", "login" => "user5"),
issue("removed", ["removed"], "Issue body description", "14", "login" => "user2"),
issue("security", ["security"], "Issue body description", "15", "login" => "user5"),
issue("all the labels", %w[breaking enhancement bug deprecated removed security], "Issue body description. \nThis part should not appear.", "9", "login" => "user9"),
issue("all the labels different order", %w[bug breaking enhancement security removed deprecated], "Issue body description", "10", "login" => "user5"),
issue("some unmapped labels", %w[tests-fail bug], "Issue body description", "11", "login" => "user5"),
issue("no mapped labels", %w[docs maintenance], "Issue body description", "12", "login" => "user5")
]
end
let(:pull_requests_with_body) do
[
pr("no labels", [], "PR body description", "20", "login" => "user1"),
pr("breaking", ["breaking"], "PR body description very long: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.", "23", "login" => "user5"),
pr("enhancement", ["enhancement"], "PR body description", "21", "login" => "user5"),
pr("bug", ["bug"], "PR body description", "22", "login" => "user5"),
pr("deprecated", ["deprecated"], "PR body description", "28", "login" => "user5"),
pr("removed", ["removed"], "PR body description", "29", "login" => "user2"),
pr("security", ["security"], "PR body description", "30", "login" => "user5"),
pr("all the labels", %w[breaking enhancement bug deprecated removed security], "PR body description. \nThis part should not appear", "24", "login" => "user5"),
pr("all the labels different order", %w[bug breaking enhancement security remove deprecated], "PR body description", "25", "login" => "user5"),
pr("some unmapped labels", %w[tests-fail bug], "PR body description", "26", "login" => "user5"),
pr("no mapped labels", %w[docs maintenance], "PR body description", "27", "login" => "user5")
]
end
subject { described_class.new(options) }
it "generates issues and pull requests with body" do
changelog = <<-CHANGELOG.gsub(/^ {10}/, "")
## [1.0.1](https://github.com/owner/repo/tree/1.0.1) (2017-12-04)
[Full Changelog](https://github.com/owner/repo/compare/1.0.0...1.0.1)
**Breaking changes:**
- **issue breaking [\\#8](https://github.com/owner/repo/issue/8)** \nIssue body description very long: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.
- **issue all the labels [\\#9](https://github.com/owner/repo/issue/9)** \nIssue body description.
- **issue all the labels different order [\\#10](https://github.com/owner/repo/issue/10)** \nIssue body description
- **pr breaking [\\#23](https://github.com/owner/repo/pull/23) ([user5](https://github.com/user5))** \nPR body description very long: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.
- **pr all the labels [\\#24](https://github.com/owner/repo/pull/24) ([user5](https://github.com/user5))** \nPR body description.
- **pr all the labels different order [\\#25](https://github.com/owner/repo/pull/25) ([user5](https://github.com/user5))** \nPR body description
**Implemented enhancements:**
- **issue enhancement [\\#6](https://github.com/owner/repo/issue/6)** \nIssue body description
- **pr enhancement [\\#21](https://github.com/owner/repo/pull/21) ([user5](https://github.com/user5))** \nPR body description
**Fixed bugs:**
- **issue bug [\\#7](https://github.com/owner/repo/issue/7)** \nIssue body description
- **issue some unmapped labels [\\#11](https://github.com/owner/repo/issue/11)** \nIssue body description
- **pr bug [\\#22](https://github.com/owner/repo/pull/22) ([user5](https://github.com/user5))** \nPR body description
- **pr some unmapped labels [\\#26](https://github.com/owner/repo/pull/26) ([user5](https://github.com/user5))** \nPR body description
**Deprecated:**
- **issue deprecated [\\#13](https://github.com/owner/repo/issue/13)** \nIssue body description
- **pr deprecated [\\#28](https://github.com/owner/repo/pull/28) ([user5](https://github.com/user5))** \nPR body description
**Removed:**
- **issue removed [\\#14](https://github.com/owner/repo/issue/14)** \nIssue body description
- **pr removed [\\#29](https://github.com/owner/repo/pull/29) ([user2](https://github.com/user2))** \nPR body description
**Security fixes:**
- **issue security [\\#15](https://github.com/owner/repo/issue/15)** \nIssue body description
- **pr security [\\#30](https://github.com/owner/repo/pull/30) ([user5](https://github.com/user5))** \nPR body description
**Closed issues:**
- **issue no labels [\\#5](https://github.com/owner/repo/issue/5)** \nIssue body description
- **issue no mapped labels [\\#12](https://github.com/owner/repo/issue/12)** \nIssue body description
**Merged pull requests:**
- **pr no labels [\\#20](https://github.com/owner/repo/pull/20) ([user1](https://github.com/user1))** \nPR body description
- **pr no mapped labels [\\#27](https://github.com/owner/repo/pull/27) ([user5](https://github.com/user5))** \nPR body description
CHANGELOG
expect(subject.generate_entry_for_tag(pull_requests_with_body, issues_with_body, "1.0.1", "1.0.1", Time.new(2017, 12, 4, 12, 0, 0, "+00:00").utc, "1.0.0")).to eq(changelog)
end
end
describe "exclude issues without labels" do
let(:options) do
Parser.default_options.merge(
user: "owner",
project: "repo",
breaking_labels: ["breaking"],
enhancement_labels: ["enhancement"],
bug_labels: ["bug"],
deprecated_labels: ["deprecated"],
removed_labels: ["removed"],
security_labels: ["security"],
add_pr_wo_labels: false,
add_issues_wo_labels: false,
verbose: false
)
end
it "generates a header and body" do
changelog = <<-CHANGELOG.gsub(/^ {10}/, "")
## [1.0.1](https://github.com/owner/repo/tree/1.0.1) (2017-12-04)
[Full Changelog](https://github.com/owner/repo/compare/1.0.0...1.0.1)
**Breaking changes:**
- issue breaking [\\#8](https://github.com/owner/repo/issue/8)
- issue all the labels [\\#9](https://github.com/owner/repo/issue/9)
- issue all the labels different order [\\#10](https://github.com/owner/repo/issue/10)
- pr breaking [\\#23](https://github.com/owner/repo/pull/23) ([user5](https://github.com/user5))
- pr all the labels [\\#24](https://github.com/owner/repo/pull/24) ([user5](https://github.com/user5))
- pr all the labels different order [\\#25](https://github.com/owner/repo/pull/25) ([user5](https://github.com/user5))
**Implemented enhancements:**
- issue enhancement [\\#6](https://github.com/owner/repo/issue/6)
- pr enhancement [\\#21](https://github.com/owner/repo/pull/21) ([user5](https://github.com/user5))
**Fixed bugs:**
- issue bug [\\#7](https://github.com/owner/repo/issue/7)
- issue some unmapped labels [\\#11](https://github.com/owner/repo/issue/11)
- pr bug [\\#22](https://github.com/owner/repo/pull/22) ([user5](https://github.com/user5))
- pr some unmapped labels [\\#26](https://github.com/owner/repo/pull/26) ([user5](https://github.com/user5))
**Deprecated:**
- issue deprecated [\\#13](https://github.com/owner/repo/issue/13)
- pr deprecated [\\#28](https://github.com/owner/repo/pull/28) ([user5](https://github.com/user5))
**Removed:**
- issue removed [\\#14](https://github.com/owner/repo/issue/14)
- pr removed [\\#29](https://github.com/owner/repo/pull/29) ([user2](https://github.com/user2))
**Security fixes:**
- issue security [\\#15](https://github.com/owner/repo/issue/15)
- pr security [\\#30](https://github.com/owner/repo/pull/30) ([user5](https://github.com/user5))
**Closed issues:**
- issue no mapped labels [\\#12](https://github.com/owner/repo/issue/12)
**Merged pull requests:**
- pr no mapped labels [\\#27](https://github.com/owner/repo/pull/27) ([user5](https://github.com/user5))
CHANGELOG
expect(subject.generate_entry_for_tag(pull_requests, issues, "1.0.1", "1.0.1", Time.new(2017, 12, 4, 12, 0, 0, "+00:00").utc, "1.0.0")).to eq(changelog)
end
end
end
describe "#parse_sections" do
before do
subject { described_class.new }
end
context "valid json" do
let(:sections_string) { "{ \"foo\": { \"prefix\": \"foofix\", \"labels\": [\"test1\", \"test2\"]}, \"bar\": { \"prefix\": \"barfix\", \"labels\": [\"test3\", \"test4\"]}}" }
let(:sections_array) do
[
Section.new(name: "foo", prefix: "foofix", labels: %w[test1 test2]),
Section.new(name: "bar", prefix: "barfix", labels: %w[test3 test4])
]
end
it "returns an array with 2 objects" do
arr = subject.send(:parse_sections, sections_string)
expect(arr.size).to eq 2
arr.each { |section| expect(section).to be_an_instance_of Section }
end
it "returns correctly constructed sections" do
require "json"
sections_json = JSON.parse(sections_string)
sections_array.each_index do |i|
aggregate_failures "checks each component" do
expect(sections_array[i].name).to eq sections_json.first[0]
expect(sections_array[i].prefix).to eq sections_json.first[1]["prefix"]
expect(sections_array[i].labels).to eq sections_json.first[1]["labels"]
expect(sections_array[i].issues).to eq []
end
sections_json.shift
end
end
context "parse also body_only" do
let(:sections_string) { "{ \"foo\": { \"prefix\": \"foofix\", \"labels\": [\"test1\", \"test2\"]}, \"bar\": { \"prefix\": \"barfix\", \"labels\": [\"test3\", \"test4\"], \"body_only\": true}}" }
it "returns correctly constructed sections" do
require "json"
parsed_sections = subject.send(:parse_sections, sections_string)
expect(parsed_sections[0].body_only).to eq false
expect(parsed_sections[1].body_only).to eq true
end
end
end
context "hash" do
let(:sections_hash) do
{
breaking: {
prefix: "**Breaking**",
labels: ["breaking"]
},
enhancements: {
prefix: "**Enhancements**",
labels: %w[feature enhancement]
},
bugs: {
prefix: "**Bugs**",
labels: ["bug"]
},
deprecated: {
prefix: "**Deprecated**",
labels: ["deprecated"]
},
removed: {
prefix: "**Removed**",
labels: ["removed"]
},
security: {
prefix: "**Security**",
labels: ["security"]
}
}
end
let(:sections_array) do
[
Section.new(name: "breaking", prefix: "**Breaking**", labels: ["breaking"]),
Section.new(name: "enhancements", prefix: "**Enhancements**", labels: %w[feature enhancement]),
Section.new(name: "bugs", prefix: "**Bugs**", labels: ["bug"]),
Section.new(name: "deprecated", prefix: "**Deprecated**", labels: ["deprecated"]),
Section.new(name: "removed", prefix: "**Removed**", labels: ["removed"]),
Section.new(name: "security", prefix: "**Security**", labels: ["security"])
]
end
it "returns an array with 6 objects" do
arr = subject.send(:parse_sections, sections_hash)
expect(arr.size).to eq 6
arr.each { |section| expect(section).to be_an_instance_of Section }
end
it "returns correctly constructed sections" do
sections_array.each_index do |i|
aggregate_failures "checks each component" do
expect(sections_array[i].name).to eq sections_hash.first[0].to_s
expect(sections_array[i].prefix).to eq sections_hash.first[1][:prefix]
expect(sections_array[i].labels).to eq sections_hash.first[1][:labels]
expect(sections_array[i].issues).to eq []
end
sections_hash.shift
end
end
end
end
describe "#sort_into_sections" do
context "default sections" do
let(:options) do
Parser.default_options.merge(
breaking_labels: ["breaking"],
enhancement_labels: ["enhancement"],
bug_labels: ["bug"],
deprecated_labels: ["deprecated"],
removed_labels: ["removed"],
security_labels: ["security"],
verbose: false
)
end
let(:issues) do
[
issue("breaking", ["breaking"]),
issue("no labels", []),
issue("enhancement", ["enhancement"]),
issue("bug", ["bug"]),
issue("deprecated", ["deprecated"]),
issue("removed", ["removed"]),
issue("security", ["security"]),
issue("all the labels", %w[breaking enhancement bug deprecated removed security]),
issue("some unmapped labels", %w[tests-fail bug]),
issue("no mapped labels", %w[docs maintenance]),
issue("excluded label", %w[wontfix]),
issue("excluded and included label", %w[breaking wontfix])
]
end
let(:pull_requests) do
[
pr("no labels", []),
pr("breaking", ["breaking"]),
pr("enhancement", ["enhancement"]),
pr("bug", ["bug"]),
pr("deprecated", ["deprecated"]),
pr("removed", ["removed"]),
pr("security", ["security"]),
pr("all the labels", %w[breaking enhancement bug deprecated removed security]),
pr("some unmapped labels", %w[tests-fail bug]),
pr("no mapped labels", %w[docs maintenance]),
pr("excluded label", %w[wontfix]),
pr("excluded and included label", %w[breaking wontfix])
]
end
subject { described_class.new(options) }
it "returns 9 sections" do
entry_sections.each { |sec| pp(sec.name) }
expect(entry_sections.size).to eq 9
end
it "returns default sections" do
default_sections.each { |default_section| expect(entry_sections.count { |section| section.name == default_section }).to eq 1 }
end
it "assigns issues to the correct sections" do
breaking_section = entry_sections.find { |section| section.name == "breaking" }
enhancement_section = entry_sections.find { |section| section.name == "enhancements" }
bug_section = entry_sections.find { |section| section.name == "bugs" }
deprecated_section = entry_sections.find { |section| section.name == "deprecated" }
removed_section = entry_sections.find { |section| section.name == "removed" }
security_section = entry_sections.find { |section| section.name == "security" }
issue_section = entry_sections.find { |section| section.name == "issues" }
merged_section = entry_sections.find { |section| section.name == "merged" }
expect(titles_for(breaking_section.issues)).to eq(["issue breaking", "issue all the labels", "pr breaking", "pr all the labels"])
expect(titles_for(enhancement_section.issues)).to eq(["issue enhancement", "pr enhancement"])
expect(titles_for(bug_section.issues)).to eq(["issue bug", "issue some unmapped labels", "pr bug", "pr some unmapped labels"])
expect(titles_for(deprecated_section.issues)).to eq(["issue deprecated", "pr deprecated"])
expect(titles_for(removed_section.issues)).to eq(["issue removed", "pr removed"])
expect(titles_for(security_section.issues)).to eq(["issue security", "pr security"])
expect(titles_for(issue_section.issues)).to eq(["issue no labels", "issue no mapped labels"])
expect(titles_for(merged_section.issues)).to eq(["pr no labels", "pr no mapped labels"])
end
end
context "configure sections and include labels" do
let(:options) do
Parser.default_options.merge(
configure_sections: "{ \"foo\": { \"prefix\": \"foofix\", \"labels\": [\"test1\", \"test2\"]}, \"bar\": { \"prefix\": \"barfix\", \"labels\": [\"test3\", \"test4\"]}}",
include_labels: %w[test1 test2 test3 test4],
verbose: false
)
end
let(:issues) do
[
issue("no labels", []),
issue("test1", ["test1"]),
issue("test3", ["test3"]),
issue("test4", ["test4"]),
issue("all the labels", %w[test4 test2 test3 test1]),
issue("some included labels", %w[unincluded test2]),
issue("no included labels", %w[unincluded again])
]
end
let(:pull_requests) do
[
pr("no labels", []),
pr("test1", ["test1"]),
pr("test3", ["test3"]),
pr("test4", ["test4"]),
pr("all the labels", %w[test4 test2 test3 test1]),
pr("some included labels", %w[unincluded test2]),
pr("no included labels", %w[unincluded again])
]
end
subject { described_class.new(options) }
it "returns 4 sections" do
expect(entry_sections.size).to eq 4
end
it "returns only configured sections" do
expect(entry_sections.count { |section| section.name == "foo" }).to eq 1
expect(entry_sections.count { |section| section.name == "bar" }).to eq 1
end
it "assigns issues to the correct sections" do
foo_section = entry_sections.find { |section| section.name == "foo" }
bar_section = entry_sections.find { |section| section.name == "bar" }
issue_section = entry_sections.find { |section| section.name == "issues" }
merged_section = entry_sections.find { |section| section.name == "merged" }
aggregate_failures "checks all sections" do
expect(titles_for(foo_section.issues)).to eq(["issue test1", "issue all the labels", "issue some included labels", "pr test1", "pr all the labels", "pr some included labels"])
expect(titles_for(bar_section.issues)).to eq(["issue test3", "issue test4", "pr test3", "pr test4"])
expect(titles_for(merged_section.issues)).to eq(["pr no labels"])
expect(titles_for(issue_section.issues)).to eq(["issue no labels"])
end
end
end
context "configure sections and exclude labels" do
let(:options) do
Parser.default_options.merge(
configure_sections: "{ \"foo\": { \"prefix\": \"foofix\", \"labels\": [\"test1\", \"test2\"]}, \"bar\": { \"prefix\": \"barfix\", \"labels\": [\"test3\", \"test4\"]}}",
exclude_labels: ["excluded"],
verbose: false
)
end
let(:issues) do
[
issue("no labels", []),
issue("test1", ["test1"]),
issue("test3", ["test3"]),
issue("test4", ["test4"]),
issue("all the labels", %w[test4 test2 test3 test1]),
issue("some excluded labels", %w[excluded test2]),
issue("excluded labels", %w[excluded again])
]
end
let(:pull_requests) do
[
pr("no labels", []),
pr("test1", ["test1"]),
pr("test3", ["test3"]),
pr("test4", ["test4"]),
pr("all the labels", %w[test4 test2 test3 test1]),
pr("some excluded labels", %w[excluded test2]),
pr("excluded labels", %w[excluded again])
]
end
subject { described_class.new(options) }
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | true |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/generator/generator_tags_spec.rb | spec/unit/generator/generator_tags_spec.rb | # frozen_string_literal: true
describe GitHubChangelogGenerator::Generator do
def tag_with_name(tag)
{
"name" => tag
}
end
def tags_from_strings(tags_strings)
tags_strings.map do |tag|
tag_with_name(tag)
end
end
describe "#detect_link_tag_time" do
let(:newer_tag) { nil }
let(:default_options) { GitHubChangelogGenerator::Parser.default_options.merge(verbose: false) }
let(:options) do
{
future_release: "2.0.0"
}
end
let(:generator) { described_class.new(default_options.merge(options)) }
subject do
generator.detect_link_tag_time(newer_tag)
end
context "When the local date is not the same as the UTC date" do
before do
# 2020-12-27T17:00:00-10:00 is 2020-12-28T03:00:00Z.
# GitHub API date & time use UTC, so this instant when converted as a
# date should be 2020-12-28.
expect(Time).to receive(:new).and_return(Time.new(2020, 12, 27, 17, 0, 0, "-10:00"))
end
it { is_expected.to eq(["2.0.0", "2.0.0", Time.gm(2020, 12, 28, 3)]) }
end
end
describe "#tag_section_mapping" do
let(:all_tags) { tags_from_strings(%w[8 7 6 5 4 3 2 1]) }
let(:sorted_tags) { all_tags }
let(:default_options) { GitHubChangelogGenerator::Parser.default_options.merge(verbose: false) }
let(:options) { {} }
let(:generator) { described_class.new(default_options.merge(options)) }
before do
allow_any_instance_of(GitHubChangelogGenerator::OctoFetcher).to receive(:fetch_all_tags).and_return(all_tags)
allow(generator).to receive(:fetch_tags_dates).with(all_tags)
allow(generator).to receive(:sort_tags_by_date).with(all_tags).and_return(sorted_tags)
generator.fetch_and_filter_tags
end
subject do
generator.tag_section_mapping
end
shared_examples_for "a section mapping" do
it { is_expected.to be_a(Hash) }
it { is_expected.to eq(expected_mapping) }
end
shared_examples_for "a full changelog" do
let(:expected_mapping) do
{
tag_with_name("8") => [tag_with_name("7"), tag_with_name("8")],
tag_with_name("7") => [tag_with_name("6"), tag_with_name("7")],
tag_with_name("6") => [tag_with_name("5"), tag_with_name("6")],
tag_with_name("5") => [tag_with_name("4"), tag_with_name("5")],
tag_with_name("4") => [tag_with_name("3"), tag_with_name("4")],
tag_with_name("3") => [tag_with_name("2"), tag_with_name("3")],
tag_with_name("2") => [tag_with_name("1"), tag_with_name("2")],
tag_with_name("1") => [nil, tag_with_name("1")]
}
end
it_behaves_like "a section mapping"
end
shared_examples_for "a changelog with some exclusions" do
let(:expected_mapping) do
{
tag_with_name("8") => [tag_with_name("6"), tag_with_name("8")],
tag_with_name("6") => [tag_with_name("4"), tag_with_name("6")],
tag_with_name("4") => [tag_with_name("3"), tag_with_name("4")],
tag_with_name("3") => [tag_with_name("1"), tag_with_name("3")],
tag_with_name("1") => [nil, tag_with_name("1")]
}
end
it_behaves_like "a section mapping"
end
context "with no constraints" do
it_behaves_like "a full changelog"
end
context "with since only" do
let(:options) { { since_tag: "6" } }
let(:expected_mapping) do
{
tag_with_name("8") => [tag_with_name("7"), tag_with_name("8")],
tag_with_name("7") => [tag_with_name("6"), tag_with_name("7")]
}
end
it_behaves_like "a section mapping"
end
context "with due only" do
let(:options) { { due_tag: "4" } }
let(:expected_mapping) do
{
tag_with_name("3") => [tag_with_name("2"), tag_with_name("3")],
tag_with_name("2") => [tag_with_name("1"), tag_with_name("2")],
tag_with_name("1") => [nil, tag_with_name("1")]
}
end
it_behaves_like "a section mapping"
end
context "with since and due" do
let(:options) { { since_tag: "2", due_tag: "5" } }
let(:expected_mapping) do
{
tag_with_name("4") => [tag_with_name("3"), tag_with_name("4")],
tag_with_name("3") => [tag_with_name("2"), tag_with_name("3")]
}
end
it_behaves_like "a section mapping"
end
context "with excluded tags" do
context "as a list of strings" do
let(:options) { { exclude_tags: %w[2 5 7] } }
it_behaves_like "a changelog with some exclusions"
end
context "as a regex" do
let(:options) { { exclude_tags: /[257]/ } }
it_behaves_like "a changelog with some exclusions"
end
context "as a regex string" do
let(:options) { { exclude_tags_regex: "[257]" } }
it_behaves_like "a changelog with some exclusions"
end
end
end
describe "#filter_included_tags_regex" do
subject { generator.filter_included_tags(tags_from_strings(%w[1 2 3])) }
context "with matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(include_tags_regex: "[23]") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[2 3])) }
end
context "with non-matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(include_tags_regex: "[45]") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[])) }
end
end
describe "#filter_excluded_tags" do
subject { generator.filter_excluded_tags(tags_from_strings(%w[1 2 3])) }
context "with matching string" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags: %w[3]) }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1 2])) }
end
context "with non-matching string" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags: %w[invalid tags]) }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1 2 3])) }
end
context "with matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags: /[23]/) }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1])) }
end
context "with non-matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags: /[abc]/) }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1 2 3])) }
end
end
describe "#filter_excluded_tags_regex" do
subject { generator.filter_excluded_tags(tags_from_strings(%w[1 2 3])) }
context "with matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags_regex: "[23]") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1])) }
end
context "with non-matching regex" do
let(:generator) { GitHubChangelogGenerator::Generator.new(exclude_tags_regex: "[45]") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1 2 3])) }
end
end
describe "#filter_since_tag" do
context "with filled array" do
subject { generator.filter_since_tag(tags_from_strings(%w[1 2 3])) }
context "with valid since tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(since_tag: "2") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[1 2])) }
context "with since tag set to the most recent tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(since_tag: "1") }
it { is_expected.to match_array(tags_from_strings(%w[1])) }
end
end
context "with invalid since tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(since_tag: "Invalid tag") }
it { expect { subject }.to raise_error(GitHubChangelogGenerator::ChangelogGeneratorError) }
end
end
context "with empty array" do
subject { generator.filter_since_tag(tags_from_strings(%w[])) }
context "with invalid since tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(since_tag: "Invalid tag") }
it { expect { subject }.to raise_error(GitHubChangelogGenerator::ChangelogGeneratorError) }
end
end
end
describe "#filter_due_tag" do
context "with filled array" do
subject { generator.filter_due_tag(tags_from_strings(%w[1 2 3])) }
context "with valid due tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(due_tag: "2") }
it { is_expected.to be_a Array }
it { is_expected.to match_array(tags_from_strings(%w[3])) }
end
context "with invalid due tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(due_tag: "Invalid tag") }
it { expect { subject }.to raise_error(GitHubChangelogGenerator::ChangelogGeneratorError) }
end
end
context "with empty array" do
subject { generator.filter_due_tag(tags_from_strings(%w[])) }
context "with invalid due tag" do
let(:generator) { GitHubChangelogGenerator::Generator.new(due_tag: "Invalid tag") }
it { expect { subject }.to raise_error(GitHubChangelogGenerator::ChangelogGeneratorError) }
end
end
end
describe "#get_time_of_tag" do
current_time = Time.now
before(:all) { @generator = GitHubChangelogGenerator::Generator.new }
context "run with nil parameter" do
it "should raise ChangelogGeneratorError" do
expect { @generator.get_time_of_tag nil }.to raise_error(GitHubChangelogGenerator::ChangelogGeneratorError)
end
end
context "fetch already filled tag" do
before { @generator.instance_variable_set :@tag_times_hash, "valid_tag" => current_time }
subject { @generator.get_time_of_tag tag_with_name("valid_tag") }
it { is_expected.to be_a_kind_of(Time) }
it { is_expected.to eq(current_time) }
end
context "fetch not filled tag" do
before do
mock = double("fake fetcher")
allow(mock).to receive_messages(fetch_date_of_tag: current_time)
@generator.instance_variable_set :@fetcher, mock
end
subject do
of_tag = @generator.get_time_of_tag(tag_with_name("valid_tag"))
of_tag
end
it { is_expected.to be_a_kind_of(Time) }
it { is_expected.to eq(current_time) }
end
end
describe "#sort_tags_by_date" do
let(:time1) { Time.now }
let(:time2) { Time.now }
let(:time3) { Time.now }
before(:all) do
@generator = GitHubChangelogGenerator::Generator.new
end
before do
@generator.instance_variable_set(:@tag_times_hash, "valid_tag1" => time1,
"valid_tag2" => time2,
"valid_tag3" => time3)
end
subject do
@generator.sort_tags_by_date(tags)
end
context "sort unsorted tags" do
let(:tags) { tags_from_strings %w[valid_tag1 valid_tag2 valid_tag3] }
it { is_expected.to be_a_kind_of(Array) }
it { is_expected.to match_array(tags.reverse!) }
end
context "sort sorted tags" do
let(:tags) { tags_from_strings %w[valid_tag3 valid_tag2 valid_tag1] }
it { is_expected.to be_a_kind_of(Array) }
it { is_expected.to match_array(tags) }
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/generator/generator_processor_spec.rb | spec/unit/generator/generator_processor_spec.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
describe Generator do
let(:default_options) { GitHubChangelogGenerator::Parser.default_options.merge(verbose: false) }
let(:options) { {} }
let(:generator) { described_class.new(default_options.merge(options)) }
let(:bad_label) { { "name" => "BAD" } }
let(:good_label) { { "name" => "GOOD" } }
describe "pull requests" do
let(:bad_pull_request) { { "pull_request" => {}, "labels" => [bad_label] } }
let(:good_pull_request) { { "pull_request" => {}, "labels" => [good_label] } }
let(:unlabeled_pull_request) { { "pull_request" => {}, "labels" => [] } }
let(:pull_requests) { [bad_pull_request, good_pull_request, unlabeled_pull_request] }
describe "#filter_wo_labels" do
subject do
generator.filter_wo_labels(pull_requests)
end
let(:expected_pull_requests) { pull_requests }
it { is_expected.to eq(expected_pull_requests) }
context "when 'add_pr_wo_labels' is false" do
let(:options) { { add_pr_wo_labels: false } }
let(:expected_pull_requests) { [bad_pull_request, good_pull_request] }
it { is_expected.to eq(expected_pull_requests) }
end
context "when 'add_pr_wo_labels' is true" do
let(:options) { { add_pr_wo_labels: true } }
it { is_expected.to eq(expected_pull_requests) }
end
end
end
describe "issues" do
let(:bad_issue) { { "labels" => [bad_label] } }
let(:good_issue) { { "labels" => [good_label] } }
let(:unlabeled_issue) { { "labels" => [] } }
let(:issues) { [bad_issue, good_issue, unlabeled_issue] }
describe "#filter_wo_labels" do
subject do
generator.filter_wo_labels(issues)
end
let(:expected_issues) { issues }
it { is_expected.to eq(expected_issues) }
context "when 'add_issues_wo_labels' is false" do
let(:options) { { add_issues_wo_labels: false } }
let(:expected_issues) { [bad_issue, good_issue] }
it { is_expected.to eq(expected_issues) }
end
context "when 'add_issues_wo_labels' is true" do
let(:options) { { add_issues_wo_labels: true } }
it { is_expected.to eq(expected_issues) }
end
end
describe "#exclude_issues_by_labels" do
subject do
generator.exclude_issues_by_labels(issues)
end
let(:expected_issues) { issues }
it { is_expected.to eq(expected_issues) }
context "when 'exclude_labels' is provided" do
let(:options) { { exclude_labels: %w[BAD BOO] } }
let(:expected_issues) { [good_issue, unlabeled_issue] }
it { is_expected.to eq(expected_issues) }
end
context "with no option given" do
subject(:generator) { described_class.new }
it "passes everything through when no option given" do
result = generator.exclude_issues_by_labels(issues)
expect(result).to eq(issues)
end
end
end
describe "#get_filtered_issues" do
subject do
generator.get_filtered_issues(issues)
end
let(:expected_issues) { issues }
it { is_expected.to eq(expected_issues) }
context "when 'exclude_labels' is provided" do
let(:options) { { exclude_labels: %w[BAD BOO] } }
let(:expected_issues) { [good_issue, unlabeled_issue] }
it { is_expected.to eq(expected_issues) }
end
context "when 'add_issues_wo_labels' is false" do
let(:options) { { add_issues_wo_labels: false } }
let(:expected_issues) { [bad_issue, good_issue] }
it { is_expected.to eq(expected_issues) }
context "with 'exclude_labels'" do
let(:options) { { add_issues_wo_labels: false, exclude_labels: %w[GOOD] } }
let(:expected_issues) { [bad_issue] }
it { is_expected.to eq(expected_issues) }
end
context "with 'include_labels'" do
let(:options) { { add_issues_wo_labels: false, include_labels: %w[GOOD] } }
let(:expected_issues) { [good_issue] }
it { is_expected.to eq(expected_issues) }
end
end
context "when 'include_labels' is specified" do
let(:options) { { include_labels: %w[GOOD] } }
let(:expected_issues) { [good_issue, unlabeled_issue] }
it { is_expected.to eq(expected_issues) }
end
end
describe "#find_issues_to_add" do
let(:issues) { [issue] }
let(:tag_name) { nil }
let(:filtered_tags) { [] }
before { generator.instance_variable_set(:@filtered_tags, filtered_tags) }
subject { generator.find_issues_to_add(issues, tag_name) }
context "issue without milestone" do
let(:issue) { { "labels" => [] } }
it { is_expected.to be_empty }
end
context "milestone title not in the filtered tags" do
let(:issue) { { "milestone" => { "title" => "a title" } } }
let(:filtered_tags) { [{ "name" => "another name" }] }
it { is_expected.to be_empty }
end
context "milestone title matches the tag name" do
let(:tag_name) { "tag name" }
let(:issue) { { "milestone" => { "title" => tag_name } } }
let(:filtered_tags) { [{ "name" => tag_name }] }
it { is_expected.to contain_exactly(issue) }
end
end
describe "#remove_issues_in_milestones" do
let(:issues) { [issue] }
context "issue without milestone" do
let(:issue) { { "labels" => [] } }
it "is not filtered" do
expect { generator.remove_issues_in_milestones(issues) }.to_not(change { issues })
end
end
context "remove issues of open milestones if option is set" do
let(:issue) { { "milestone" => { "state" => "open" } } }
let(:options) { { issues_of_open_milestones: false } }
it "is filtered" do
expect { generator.remove_issues_in_milestones(issues) }.to change { issues }.to([])
end
end
context "milestone in the tag list" do
let(:milestone_name) { "milestone name" }
let(:issue) { { "milestone" => { "title" => milestone_name } } }
it "is filtered" do
generator.instance_variable_set(:@filtered_tags, [{ "name" => milestone_name }])
expect { generator.remove_issues_in_milestones(issues) }.to change { issues }.to([])
end
end
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/generator/section_spec.rb | spec/unit/generator/section_spec.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
RSpec.describe Section do
let(:options) { {} }
subject(:section) { described_class.new(options) }
describe "#encapsulate_string" do
let(:string) { "" }
context "with the empty string" do
it "returns the string" do
expect(section.send(:encapsulate_string, string)).to eq string
end
end
context "with a string with an escape-needing character in it" do
let(:string) { "<Inside> and outside" }
it "returns the string escaped" do
expect(section.send(:encapsulate_string, string)).to eq '\\<Inside\\> and outside'
end
end
context "with a backticked string with an escape-needing character in it" do
let(:string) { 'back `\` slash' }
it "returns the string" do
expect(section.send(:encapsulate_string, string)).to eq 'back `\` slash'
end
end
end
describe "#normalize_body" do
context "it should remove CR" do
let(:body) { "Some content from GitHub\r\n\r\nUser is describing something" }
it "returns a cleaned body" do
expect(section.send(:normalize_body, body)).to eq "Some content from GitHub\n\nUser is describing something"
end
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/spec/unit/generator/generator_spec.rb | spec/unit/generator/generator_spec.rb | # frozen_string_literal: true
require "github_changelog_generator/generator/generator"
RSpec.describe GitHubChangelogGenerator::Generator do
let(:header) { "# Changelog" }
let(:generator) { described_class.new({ header: header }) }
let(:content) do
<<~'BASE'
## [1.3.10](https://github.com/xxx/yyy/tree/1.3.10) (2015-03-18)
[Full Changelog](https://github.com/xxx/yyy/compare/1.3.9...1.3.10)
**Fixed bugs:**
BASE
end
let(:footer) do
<<~CREDIT
\\* *This Changelog was automatically generated \
by [github_changelog_generator]\
(https://github.com/github-changelog-generator/github-changelog-generator)*
CREDIT
end
context "when the given base file has previously appended template messages" do
describe "#remove_old_fixed_string" do
it "removes old template headers and footers" do
log = +"#{header}\n\n#{header}\n#{header}#{content}\n\n#{footer}\n#{footer}#{footer}"
expect(generator.send(:remove_old_fixed_string, log)).to eq content
end
end
end
context "when plain contents string was given" do
describe "#insert_fixed_string" do
it "append template messages at header and footer" do
log = String.new(content)
ans = "#{header}\n\n#{content}\n\n#{footer}"
expect(generator.send(:insert_fixed_string, log)).to eq ans
end
end
end
describe "#add_first_occurring_tag_to_prs" do
def sha(num)
base = num.to_s
pad_length = 40 - base.length
"#{'a' * pad_length}#{base}"
end
let(:release_branch_name) { "release" }
let(:generator) { described_class.new({ release_branch: release_branch_name }) }
let(:fake_fetcher) do
instance_double(GitHubChangelogGenerator::OctoFetcher,
fetch_tag_shas: nil,
fetch_comments_async: nil)
end
before do
allow(fake_fetcher)
.to receive(:commits_in_branch).with(release_branch_name)
.and_return([sha(1), sha(2), sha(3), sha(4)])
allow(GitHubChangelogGenerator::OctoFetcher).to receive(:new).and_return(fake_fetcher)
end
it "associates prs to the oldest tag containing the merge commit" do
prs = [{ "number" => "23", "events" => [{ "event" => "merged", "commit_id" => sha(2) }] }]
tags = [
{ "name" => "newer2.0", "shas_in_tag" => [sha(1), sha(2), sha(3)] },
{ "name" => "older1.0", "shas_in_tag" => [sha(1), sha(2)] }
]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to eq "older1.0"
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).not_to have_received(:fetch_comments_async)
end
end
it "detects prs merged in the release branch" do
prs = [{ "number" => "23", "events" => [{ "event" => "merged", "commit_id" => sha(4) }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to be_nil
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).not_to have_received(:fetch_comments_async)
end
end
it "detects closed prs marked as rebased in a tag" do
prs = [{ "number" => "23", "comments" => [{ "body" => "rebased commit: #{sha(2)}" }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to eq "v1.0"
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).to have_received(:fetch_comments_async)
end
end
it "detects closed prs marked as rebased in the release branch" do
prs = [{ "number" => "23", "comments" => [{ "body" => "rebased commit: #{sha(4)}" }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to be_nil
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).to have_received(:fetch_comments_async)
end
end
it "leaves prs merged in another branch" do
prs = [{ "number" => "23", "events" => [{ "event" => "merged", "commit_id" => sha(5) }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to eq prs
expect(prs.first["first_occurring_tag"]).to be_nil
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).to have_received(:fetch_comments_async)
end
end
it "detects prs merged elsewhere and marked as rebased in a tag" do
prs = [{ "number" => "23",
"events" => [{ "event" => "merged", "commit_id" => sha(5) }],
"comments" => [{ "body" => "rebased commit: #{sha(2)}" }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to eq "v1.0"
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).to have_received(:fetch_comments_async)
end
end
it "detects prs merged elsewhere and marked as rebased in the release branch" do
prs = [{ "number" => "23",
"events" => [{ "event" => "merged", "commit_id" => sha(5) }],
"comments" => [{ "body" => "rebased commit: #{sha(4)}" }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
prs_left = generator.send(:add_first_occurring_tag_to_prs, tags, prs)
aggregate_failures do
expect(prs_left).to be_empty
expect(prs.first["first_occurring_tag"]).to be_nil
expect(fake_fetcher).to have_received(:fetch_tag_shas)
expect(fake_fetcher).to have_received(:fetch_comments_async)
end
end
it "raises an error for closed prs marked as rebased to an unknown commit" do
prs = [{ "number" => "23", "comments" => [{ "body" => "rebased commit: #{sha(5)}" }] }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
expect { generator.send(:add_first_occurring_tag_to_prs, tags, prs) }
.to raise_error StandardError, "PR 23 has a rebased SHA comment but that SHA was not found in the release branch or any tags"
end
it "raises an error for prs without merge event or rebase comment" do
prs = [{ "number" => "23" }]
tags = [{ "name" => "v1.0", "shas_in_tag" => [sha(1), sha(2)] }]
expect { generator.send(:add_first_occurring_tag_to_prs, tags, prs) }
.to raise_error StandardError, "No merge sha found for PR 23 via the GitHub API"
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator.rb | lib/github_changelog_generator.rb | # frozen_string_literal: true
require "octokit"
require "faraday-http-cache"
require "logger"
require "active_support"
require "active_support/core_ext/object/blank"
require "json"
require "benchmark"
require "github_changelog_generator/helper"
require "github_changelog_generator/options"
require "github_changelog_generator/parser"
require "github_changelog_generator/parser_file"
require "github_changelog_generator/generator/generator"
require "github_changelog_generator/version"
require "github_changelog_generator/reader"
# The main module, where placed all classes (now, at least)
module GitHubChangelogGenerator
# Main class and entry point for this script.
class ChangelogGenerator
# Class, responsible for whole changelog generation cycle
# @return initialised instance of ChangelogGenerator
def initialize(params = ARGV)
@options = Parser.parse_options(params)
@generator = Generator.new(@options)
end
# The entry point of this script to generate changelog
# @raise (ChangelogGeneratorError) Is thrown when one of specified tags was not found in list of tags.
def run
log = generator.compound_changelog
if options.write_to_file?
output_filename = options[:output].to_s
File.open(output_filename, "wb") { |file| file.write(log) }
puts "Done!"
puts "Generated log placed in #{File.absolute_path(output_filename)}"
else
puts log
end
end
private
attr_reader :generator, :options
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/task.rb | lib/github_changelog_generator/task.rb | # frozen_string_literal: true
require "rake"
require "rake/tasklib"
require "github_changelog_generator"
module GitHubChangelogGenerator
class RakeTask < ::Rake::TaskLib
include ::Rake::DSL if defined?(::Rake::DSL)
OPTIONS = %w[ user project token date_format output
bug_prefix enhancement_prefix issue_prefix
header merge_prefix issues
add_issues_wo_labels add_pr_wo_labels
pulls filter_issues_by_milestone author
unreleased_only unreleased unreleased_label
compare_link include_labels exclude_labels
bug_labels enhancement_labels include_tags_regex
between_tags exclude_tags exclude_tags_regex since_tag max_issues
github_site github_endpoint simple_list
future_release release_branch verbose release_url
base configure_sections add_sections http_cache]
OPTIONS.each do |o|
attr_accessor o.to_sym
end
# Public: Initialise a new GitHubChangelogGenerator::RakeTask.
#
# Example
#
# GitHubChangelogGenerator::RakeTask.new
def initialize(*args, &task_block)
super()
@name = args.shift || :changelog
define(args, &task_block)
end
def define(args, &task_block)
desc "Generate a Changelog from GitHub"
yield(*[self, args].slice(0, task_block.arity)) if task_block
# clear any (auto-)pre-existing task
Rake::Task[@name].clear if Rake::Task.task_defined?(@name)
task @name do
# mimick parse_options
options = Parser.default_options
OPTIONS.each do |o|
v = instance_variable_get("@#{o}")
options[o.to_sym] = v unless v.nil?
end
abort "user and project are required." unless options[:user] && options[:project]
generator = Generator.new options
log = generator.compound_changelog
output_filename = options[:output].to_s
File.open(output_filename, "w") { |file| file.write(log) }
puts "Done!"
puts "Generated log placed in #{File.absolute_path(output_filename)}"
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/version.rb | lib/github_changelog_generator/version.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
VERSION = "1.16.4"
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/options.rb | lib/github_changelog_generator/options.rb | # frozen_string_literal: true
require "delegate"
require "github_changelog_generator/helper"
module GitHubChangelogGenerator
# This class wraps Options, and knows a list of known options. Others options
# will raise exceptions.
class Options < SimpleDelegator
# Raised on initializing with unknown keys in the values hash,
# and when trying to store a value on an unknown key.
UnsupportedOptionError = Class.new(ArgumentError)
# List of valid option names
KNOWN_OPTIONS = %i[
add_issues_wo_labels
add_pr_wo_labels
add_sections
author
base
between_tags
breaking_labels
breaking_prefix
bug_labels
bug_prefix
cache_file
cache_log
config_file
compare_link
configure_sections
date_format
deprecated_labels
deprecated_prefix
due_tag
enhancement_labels
enhancement_prefix
exclude_labels
exclude_tags
exclude_tags_regex
filter_issues_by_milestone
issues_of_open_milestones
frontmatter
future_release
github_endpoint
github_site
header
http_cache
include_labels
include_tags_regex
issue_prefix
issue_line_labels
issue_line_body
issues
max_issues
merge_prefix
output
project
pulls
release_branch
release_url
removed_labels
removed_prefix
require
security_labels
security_prefix
simple_list
since_tag
since_commit
ssl_ca_file
summary_labels
summary_prefix
token
unreleased
unreleased_label
unreleased_only
user
usernames_as_github_logins
verbose
]
# @param values [Hash]
#
# @raise [UnsupportedOptionError] if given values contain unknown options
def initialize(values)
super(values)
unsupported_options.any? && raise(UnsupportedOptionError, unsupported_options.inspect)
end
# Set option key to val.
#
# @param key [Symbol]
# @param val [Object]
#
# @raise [UnsupportedOptionError] when trying to set an unknown option
def []=(key, val)
supported_option?(key) || raise(UnsupportedOptionError, key.inspect)
values[key] = val
end
# @return [Hash]
def to_hash
values
end
# Loads the configured Ruby files from the --require option.
def load_custom_ruby_files
self[:require].each { |f| require f }
end
# Pretty-prints a censored options hash, if :verbose.
def print_options
return unless self[:verbose]
Helper.log.info "Using these options:"
# For ruby 2.5.0+
censored_values.each do |key, value|
print(key.inspect, "=>", value.inspect)
puts ""
end
puts ""
end
# Boolean method for whether the user is using configure_sections
def configure_sections?
!self[:configure_sections].nil? && !self[:configure_sections].empty?
end
# Boolean method for whether the user is using add_sections
def add_sections?
!self[:add_sections].nil? && !self[:add_sections].empty?
end
# @return [Boolean] whether write to `:output`
def write_to_file?
self[:output].present?
end
private
def values
__getobj__
end
# Returns a censored options hash.
#
# @return [Hash] The GitHub `:token` key is censored in the output.
def censored_values
values.clone.tap { |opts| opts[:token] = censored_token(opts[:token]) }
end
def censored_token(opts_token)
if !opts_token.nil?
"Used token from options"
elsif ENV["CHANGELOG_GITHUB_TOKEN"]
"Used token from environment variable"
else
"No token used"
end
end
def unsupported_options
values.keys - KNOWN_OPTIONS
end
def supported_option?(key)
KNOWN_OPTIONS.include?(key)
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/reader.rb | lib/github_changelog_generator/reader.rb | # frozen_string_literal: true
#
# Author:: Enrico Stahn <mail@enricostahn.com>
#
# Copyright 2014, Zanui, <engineering@zanui.com.au>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module GitHubChangelogGenerator
# A Reader to read an existing ChangeLog file and return a structured object
#
# Example:
# reader = GitHubChangelogGenerator::Reader.new
# content = reader.read('./CHANGELOG.md')
class Reader
def initialize(options = {})
defaults = {
heading_level: "##",
heading_structures: [
/^## \[(?<version>.+?)\](\((?<url>.+?)\))?( \((?<date>.+?)\))?$/, # rubocop:disable Lint/MixedRegexpCaptureTypes
/^## (?<version>.+?)( \((?<date>.+?)\))?$/ # rubocop:disable Lint/MixedRegexpCaptureTypes
]
}
@options = options.merge(defaults)
@heading_level = @options[:heading_level]
@heading_structures = @options[:heading_structures]
end
# Parse a single heading and return a Hash
#
# The following heading structures are currently valid:
# - ## [v1.0.2](https://github.com/zanui/chef-thumbor/tree/v1.0.1) (2015-03-24)
# - ## [v1.0.2](https://github.com/zanui/chef-thumbor/tree/v1.0.1)
# - ## [v1.0.2] (2015-03-24)
# - ## [v1.0.2]
# - ## v1.0.2 (2015-03-24)
# - ## v1.0.2
#
# @param [String] heading Heading from the ChangeLog File
# @return [Hash] Returns a structured Hash with version, url and date
def parse_heading(heading)
captures = { "version" => nil, "url" => nil, "date" => nil }
@heading_structures.each do |regexp|
matches = Regexp.new(regexp).match(heading)
if matches
captures.merge!(Hash[matches.names.zip(matches.captures)])
break
end
end
captures
end
# Parse the given ChangeLog data into a list of Hashes
#
# @param [String] data File data from the ChangeLog.md
# @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
def parse(data)
sections = data.split(/^## .+?$/)
headings = data.scan(/^## .+?$/)
headings.each_with_index.map do |heading, index|
section = parse_heading(heading)
section["content"] = sections.at(index + 1)
section
end
end
def read(file_path)
parse File.read(file_path)
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/parser.rb | lib/github_changelog_generator/parser.rb | # frozen_string_literal: true
require "github_changelog_generator/helper"
require "github_changelog_generator/argv_parser"
require "github_changelog_generator/parser_file"
require "github_changelog_generator/file_parser_chooser"
module GitHubChangelogGenerator
class Parser
class << self
PARSERS = [
ArgvParser, # Parse arguments first to get initial options populated
FileParserChooser, # Then parse possible configuration files
ArgvParser # Lastly parse arguments again to keep the given arguments the strongest
].freeze
def parse_options(argv = ARGV)
options = default_options
PARSERS.each do |parser|
parser.new(options).parse!(argv)
end
abort_if_user_and_project_not_given!(options)
options.print_options
options
end
def abort_if_user_and_project_not_given!(options)
return if options[:user] && options[:project]
warn "Configure which user and project to work on."
warn "Options --user and --project, or settings to that effect. See --help for more."
warn ArgvParser.banner
Kernel.abort
end
# @return [Options] Default options
def default_options
Options.new(
date_format: "%Y-%m-%d",
output: "CHANGELOG.md",
base: "HISTORY.md",
issues: true,
add_issues_wo_labels: true,
add_pr_wo_labels: true,
pulls: true,
filter_issues_by_milestone: true,
issues_of_open_milestones: true,
author: true,
unreleased: true,
unreleased_label: "Unreleased",
compare_link: true,
exclude_labels: ["duplicate", "question", "invalid", "wontfix", "Duplicate", "Question", "Invalid", "Wontfix", "Meta: Exclude From Changelog"],
summary_labels: ["Release summary", "release-summary", "Summary", "summary"],
breaking_labels: ["backwards-incompatible", "Backwards incompatible", "breaking"],
enhancement_labels: ["enhancement", "Enhancement", "Type: Enhancement"],
bug_labels: ["bug", "Bug", "Type: Bug"],
deprecated_labels: ["deprecated", "Deprecated", "Type: Deprecated"],
removed_labels: ["removed", "Removed", "Type: Removed"],
security_labels: ["security", "Security", "Type: Security"],
configure_sections: {},
add_sections: {},
issue_line_labels: [],
max_issues: nil,
simple_list: false,
ssl_ca_file: nil,
verbose: true,
header: "# Changelog",
merge_prefix: "**Merged pull requests:**",
issue_prefix: "**Closed issues:**",
summary_prefix: "",
breaking_prefix: "**Breaking changes:**",
enhancement_prefix: "**Implemented enhancements:**",
bug_prefix: "**Fixed bugs:**",
deprecated_prefix: "**Deprecated:**",
removed_prefix: "**Removed:**",
security_prefix: "**Security fixes:**",
http_cache: true,
require: [],
config_file: ".github_changelog_generator"
)
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/parser_file.rb | lib/github_changelog_generator/parser_file.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
ParserError = Class.new(StandardError)
# ParserFile is a configuration file reader which sets options in the
# given Hash.
#
# In your project's root, you can put a file named
# <tt>.github_changelog_generator</tt> to override defaults.
#
# Example:
# header_label=# My Super Changelog
# ; Comments are allowed
# future-release=5.0.0
# # Ruby-style comments, too
# since-tag=1.0.0
#
# The configuration format is <tt>some-key=value</tt> or <tt>some_key=value</tt>.
#
class ParserFile
# @param options [Hash] options to be configured from file contents
# @param io [nil, IO] configuration file handle
def initialize(options, io = nil)
@options = options
@io = io
end
# Sets options using configuration file content
def parse!
return unless @io
@io.each_with_index { |line, i| parse_line!(line, i + 1) }
@io.close
end
private
def parse_line!(line, line_number)
return if non_configuration_line?(line)
option_name, value = extract_pair(line)
@options[option_key_for(option_name)] = convert_value(value, option_name)
rescue StandardError
raise ParserError, "Failed on line ##{line_number}: \"#{line.gsub(/[\n\r]+/, '')}\""
end
# Returns true if the line starts with a pound sign or a semi-colon.
def non_configuration_line?(line)
line =~ /^[\#;]/ || line =~ /^\s+$/
end
# Returns a the option name as a symbol and its string value sans newlines.
#
# @param line [String] unparsed line from config file
# @return [Array<Symbol, String>]
def extract_pair(line)
key, value = line.split("=", 2)
[key.tr("-", "_").to_sym, value.gsub(/[\n\r]+/, "")]
end
KNOWN_ARRAY_KEYS = %i[exclude_labels include_labels
summary_labels breaking_labels enhancement_labels bug_labels
deprecated_labels removed_labels security_labels
issue_line_labels between_tags exclude_tags]
KNOWN_INTEGER_KEYS = [:max_issues]
def convert_value(value, option_name)
if KNOWN_ARRAY_KEYS.include?(option_name)
value.split(",")
elsif KNOWN_INTEGER_KEYS.include?(option_name)
value.to_i
elsif value =~ /^(true|t|yes|y|1)$/i
true
elsif value =~ /^(false|f|no|n|0)$/i
false
else
value
end
end
IRREGULAR_OPTIONS = {
bugs_label: :bug_prefix,
enhancement_label: :enhancement_prefix,
issues_label: :issue_prefix,
header_label: :header,
front_matter: :frontmatter,
pr_label: :merge_prefix,
breaking_label: :breaking_prefix,
issues_wo_labels: :add_issues_wo_labels,
pr_wo_labels: :add_pr_wo_labels,
pull_requests: :pulls,
filter_by_milestone: :filter_issues_by_milestone,
github_api: :github_endpoint
}
def option_key_for(option_name)
IRREGULAR_OPTIONS.fetch(option_name) { option_name }
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/file_parser_chooser.rb | lib/github_changelog_generator/file_parser_chooser.rb | # frozen_string_literal: true
require "pathname"
module GitHubChangelogGenerator
class FileParserChooser
def initialize(options)
@options = options
@config_file = Pathname.new(options[:config_file])
end
def parse!(_argv)
return nil unless (path = resolve_path)
ParserFile.new(@options, File.open(path)).parse!
end
def resolve_path
return @config_file if @config_file.exist?
path = @config_file.expand_path
return path if File.exist?(path)
nil
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/octo_fetcher.rb | lib/github_changelog_generator/octo_fetcher.rb | # frozen_string_literal: true
require "tmpdir"
require "async"
require "async/barrier"
require "async/semaphore"
require "async/http/faraday"
module GitHubChangelogGenerator
# A Fetcher responsible for all requests to GitHub and all basic manipulation with related data
# (such as filtering, validating, e.t.c)
#
# Example:
# fetcher = GitHubChangelogGenerator::OctoFetcher.new(options)
class OctoFetcher
PER_PAGE_NUMBER = 100
MAXIMUM_CONNECTIONS = 50
MAX_FORBIDDEN_RETRIES = 100
CHANGELOG_GITHUB_TOKEN = "CHANGELOG_GITHUB_TOKEN"
GH_RATE_LIMIT_EXCEEDED_MSG = "Warning: Can't finish operation: GitHub API rate limit exceeded, changelog may be " \
"missing some issues. You can limit the number of issues fetched using the `--max-issues NUM` argument."
NO_TOKEN_PROVIDED = "Warning: No token provided (-t option) and variable $CHANGELOG_GITHUB_TOKEN was not found. " \
"This script can make only 50 requests to GitHub API per hour without a token!"
# @param options [Hash] Options passed in
# @option options [String] :user GitHub username
# @option options [String] :project GitHub project
# @option options [String] :since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. eg. Time.parse("2016-01-01 10:00:00").iso8601
# @option options [Boolean] :http_cache Use ActiveSupport::Cache::FileStore to cache http requests
# @option options [Boolean] :cache_file If using http_cache, this is the cache file path
# @option options [Boolean] :cache_log If using http_cache, this is the cache log file path
def initialize(options = {})
@options = options || {}
@user = @options[:user]
@project = @options[:project]
@since = @options[:since]
@http_cache = @options[:http_cache]
@commits = []
@branches = nil
@graph = nil
@client = nil
@commits_in_tag_cache = {}
end
def middleware
Faraday::RackBuilder.new do |builder|
if @http_cache
cache_file = @options.fetch(:cache_file) { File.join(Dir.tmpdir, "github-changelog-http-cache") }
cache_log = @options.fetch(:cache_log) { File.join(Dir.tmpdir, "github-changelog-logger.log") }
builder.use(
Faraday::HttpCache,
serializer: Marshal,
store: ActiveSupport::Cache::FileStore.new(cache_file),
logger: Logger.new(cache_log),
shared_cache: false
)
end
builder.use Octokit::Response::RaiseError
builder.adapter :async_http
end
end
def connection_options
ca_file = @options[:ssl_ca_file] || ENV["SSL_CA_FILE"] || File.expand_path("ssl_certs/cacert.pem", __dir__)
Octokit.connection_options.merge({ ssl: { ca_file: ca_file } })
end
def client_options
options = {
middleware: middleware,
connection_options: connection_options
}
if (github_token = fetch_github_token)
options[:access_token] = github_token
end
if (endpoint = @options[:github_endpoint])
options[:api_endpoint] = endpoint
end
options
end
def client
@client ||= Octokit::Client.new(client_options)
end
DEFAULT_REQUEST_OPTIONS = { per_page: PER_PAGE_NUMBER }
# Fetch all tags from repo
#
# @return [Array <Hash>] array of tags
def fetch_all_tags
print "Fetching tags...\r" if @options[:verbose]
check_github_response { github_fetch_tags }
end
def get_all_tags # rubocop:disable Naming/AccessorMethodName
warn("[DEPRECATED] GitHubChangelogGenerator::OctoFetcher#get_all_tags is deprecated; use fetch_all_tags instead.")
fetch_all_tags
end
# Returns the number of pages for a API call
#
# @return [Integer] number of pages for this API call in total
# @param [Object] request_options
# @param [Object] method
# @param [Object] client
def calculate_pages(client, method, request_options)
# Makes the first API call so that we can call last_response
check_github_response do
client.send(method, user_project, DEFAULT_REQUEST_OPTIONS.merge(request_options))
end
last_response = client.last_response
if (last_pg = last_response.rels[:last])
querystring_as_hash(last_pg.href)["page"].to_i
else
1
end
end
# Fill input array with tags
#
# @return [Array <Hash>] array of tags in repo
def github_fetch_tags
tags = []
page_i = 0
count_pages = calculate_pages(client, "tags", {})
iterate_pages(client, "tags") do |new_tags|
page_i += PER_PAGE_NUMBER
print_in_same_line("Fetching tags... #{page_i}/#{count_pages * PER_PAGE_NUMBER}")
tags.concat(new_tags)
end
print_empty_line
if tags.count == 0
Helper.log.warn "Warning: Can't find any tags in repo. \
Make sure, that you push tags to remote repo via 'git push --tags'"
else
Helper.log.info "Found #{tags.count} tags"
end
# tags are a Sawyer::Resource. Convert to hash
tags.map { |resource| stringify_keys_deep(resource.to_hash) }
end
def closed_pr_options
@closed_pr_options ||= {
filter: "all", labels: nil, state: "closed"
}.tap { |options| options[:since] = @since if @since }
end
# This method fetch all closed issues and separate them to pull requests and pure issues
# (pull request is kind of issue in term of GitHub)
#
# @return [Tuple] with (issues [Array <Hash>], pull-requests [Array <Hash>])
def fetch_closed_issues_and_pr
print "Fetching closed issues...\r" if @options[:verbose]
issues = []
page_i = 0
count_pages = calculate_pages(client, "issues", closed_pr_options)
iterate_pages(client, "issues", **closed_pr_options) do |new_issues|
page_i += PER_PAGE_NUMBER
print_in_same_line("Fetching issues... #{page_i}/#{count_pages * PER_PAGE_NUMBER}")
issues.concat(new_issues)
break if @options[:max_issues] && issues.length >= @options[:max_issues]
end
print_empty_line
Helper.log.info "Received issues: #{issues.count}"
# separate arrays of issues and pull requests:
issues.map { |issue| stringify_keys_deep(issue.to_hash) }
.partition { |issue_or_pr| issue_or_pr["pull_request"].nil? }
end
# Fetch all pull requests. We need them to detect :merged_at parameter
#
# @return [Array <Hash>] all pull requests
def fetch_closed_pull_requests
pull_requests = []
options = { state: "closed" }
page_i = 0
count_pages = calculate_pages(client, "pull_requests", options)
iterate_pages(client, "pull_requests", **options) do |new_pr|
page_i += PER_PAGE_NUMBER
log_string = "Fetching merged dates... #{page_i}/#{count_pages * PER_PAGE_NUMBER}"
print_in_same_line(log_string)
pull_requests.concat(new_pr)
end
print_empty_line
Helper.log.info "Pull Request count: #{pull_requests.count}"
pull_requests.map { |pull_request| stringify_keys_deep(pull_request.to_hash) }
end
# Fetch event for all issues and add them to 'events'
#
# @param [Array] issues
# @return [Void]
def fetch_events_async(issues)
i = 0
# Add accept option explicitly for disabling the warning of preview API.
preview = { accept: Octokit::Preview::PREVIEW_TYPES[:project_card_events] }
barrier = Async::Barrier.new
semaphore = Async::Semaphore.new(MAXIMUM_CONNECTIONS, parent: barrier)
Sync do
client = self.client
issues.each do |issue|
semaphore.async do
issue["events"] = []
iterate_pages(client, "issue_events", issue["number"], **preview) do |new_event|
issue["events"].concat(new_event)
end
issue["events"] = issue["events"].map { |event| stringify_keys_deep(event.to_hash) }
print_in_same_line("Fetching events for issues and PR: #{i + 1}/#{issues.count}")
i += 1
end
end
barrier.wait
# to clear line from prev print
print_empty_line
end
Helper.log.info "Fetching events for issues and PR: #{i}"
end
# Fetch comments for PRs and add them to "comments"
#
# @param [Array] prs The array of PRs.
# @return [Void] No return; PRs are updated in-place.
def fetch_comments_async(prs)
barrier = Async::Barrier.new
semaphore = Async::Semaphore.new(MAXIMUM_CONNECTIONS, parent: barrier)
Sync do
client = self.client
prs.each do |pr|
semaphore.async do
pr["comments"] = []
iterate_pages(client, "issue_comments", pr["number"]) do |new_comment|
pr["comments"].concat(new_comment)
end
pr["comments"] = pr["comments"].map { |comment| stringify_keys_deep(comment.to_hash) }
end
end
barrier.wait
end
nil
end
# Fetch tag time from repo
#
# @param [Hash] tag GitHub data item about a Tag
#
# @return [Time] time of specified tag
def fetch_date_of_tag(tag)
commit_data = fetch_commit(tag["commit"]["sha"])
commit_data = stringify_keys_deep(commit_data.to_hash)
commit_data["commit"]["committer"]["date"]
end
# Fetch commit for specified event
#
# @param [String] commit_id the SHA of a commit to fetch
# @return [Hash]
def fetch_commit(commit_id)
found = commits.find do |commit|
commit["sha"] == commit_id
end
if found
stringify_keys_deep(found.to_hash)
else
client = self.client
# cache miss; don't add to @commits because unsure of order.
check_github_response do
commit = client.commit(user_project, commit_id)
commit = stringify_keys_deep(commit.to_hash)
commit
end
end
end
# Fetch all commits
#
# @return [Array] Commits in a repo.
def commits
if @commits.empty?
Sync do
barrier = Async::Barrier.new
semaphore = Async::Semaphore.new(MAXIMUM_CONNECTIONS, parent: barrier)
branch = @options[:release_branch] || default_branch
if (since_commit = @options[:since_commit])
iterate_pages(client, "commits_since", since_commit, branch, parent: semaphore) do |new_commits|
@commits.concat(new_commits)
end
else
iterate_pages(client, "commits", branch, parent: semaphore) do |new_commits|
@commits.concat(new_commits)
end
end
barrier.wait
@commits.sort! do |b, a|
a[:commit][:author][:date] <=> b[:commit][:author][:date]
end
end
end
@commits
end
# Return the oldest commit in a repo
#
# @return [Hash] Oldest commit in the github git history.
def oldest_commit
commits.last
end
# @return [String] Default branch of the repo
def default_branch
@default_branch ||= client.repository(user_project)[:default_branch]
end
# @param [String] name
# @return [Array<String>]
def commits_in_branch(name)
@branches ||= lambda do
iterate_pages(client, "branches") do |branches|
branches_map = branches.to_h { |branch| [branch[:name], branch] }
return branches_map if branches_map[name]
end
{}
end.call
if (branch = @branches[name])
commits_in_tag(branch[:commit][:sha])
else
[]
end
end
# Fetch all SHAs occurring in or before a given tag and add them to
# "shas_in_tag"
#
# @param [Array] tags The array of tags.
# @return void
def fetch_tag_shas(tags)
# Reverse the tags array to gain max benefit from the @commits_in_tag_cache
tags.reverse_each do |tag|
tag["shas_in_tag"] = commits_in_tag(tag["commit"]["sha"])
end
end
private
# @param [Set] shas
# @param [Object] sha
def commits_in_tag(sha, shas = Set.new)
# Reduce multiple runs for the same tag
return @commits_in_tag_cache[sha] if @commits_in_tag_cache.key?(sha)
@graph ||= commits.map { |commit| [commit[:sha], commit] }.to_h
return shas unless (current = @graph[sha])
queue = [current]
while queue.any?
commit = queue.shift
if @commits_in_tag_cache.key?(commit[:sha])
# If we've already processed this sha in a previous run, just grab
# its parents from the cache
shas.merge(@commits_in_tag_cache[commit[:sha]])
elsif shas.include?(commit[:sha])
# If we've already processed this sha in the current run, stop there
# for the current commit because its parents have already been
# queued/processed. Jump to the next queued commit.
next
else
shas.add(commit[:sha])
commit[:parents].each do |p|
queue.push(@graph[p[:sha]]) unless shas.include?(p[:sha])
end
end
end
@commits_in_tag_cache[sha] = shas
shas
end
# @param [Object] indata
def stringify_keys_deep(indata)
case indata
when Array
indata.map do |value|
stringify_keys_deep(value)
end
when Hash
indata.each_with_object({}) do |(key, value), output|
output[key.to_s] = stringify_keys_deep(value)
end
else
indata
end
end
# Exception raised to warn about moved repositories.
MovedPermanentlyError = Class.new(RuntimeError)
# Iterates through all pages until there are no more :next pages to follow
# yields the result per page
#
# @param [Octokit::Client] client
# @param [String] method (eg. 'tags')
# @param [Array] arguments
# @param [Async::Semaphore] parent
#
# @yield [Sawyer::Resource] An OctoKit-provided response (which can be empty)
#
# @return [void]
# @param [Hash] options
def iterate_pages(client, method, *arguments, parent: nil, **options)
options = DEFAULT_REQUEST_OPTIONS.merge(options)
check_github_response { client.send(method, user_project, *arguments, **options) }
last_response = client.last_response.tap do |response|
raise(MovedPermanentlyError, response.data[:url]) if response.status == 301
end
yield(last_response.data)
if parent.nil?
# The snail visits one leaf at a time:
until (next_one = last_response.rels[:next]).nil?
last_response = check_github_response { next_one.get }
yield(last_response.data)
end
elsif (last = last_response.rels[:last])
# OR we bring out the gatling gun:
parameters = querystring_as_hash(last.href)
last_page = Integer(parameters["page"])
(2..last_page).each do |page|
parent.async do
data = check_github_response { client.send(method, user_project, *arguments, page: page, **options) }
yield data
end
end
end
end
# This is wrapper with rescue block
#
# @return [Object] returns exactly the same, what you put in the block, but wrap it with begin-rescue block
# @param [Proc] block
def check_github_response
yield
rescue MovedPermanentlyError => e
fail_with_message(e, "The repository has moved, update your configuration")
rescue Octokit::TooManyRequests => e
resets_in = client.rate_limit.resets_in
Helper.log.error("#{e.class} #{e.message}; sleeping for #{resets_in}s...")
if (task = Async::Task.current?)
task.sleep(resets_in)
else
sleep(resets_in)
end
retry
rescue Octokit::Forbidden => e
fail_with_message(e, "Exceeded retry limit")
rescue Octokit::Unauthorized => e
fail_with_message(e, "Error: wrong GitHub token")
end
# Presents the exception, and the aborts with the message.
# @param [Object] message
# @param [Object] error
def fail_with_message(error, message)
Helper.log.error("#{error.class}: #{error.message}")
sys_abort(message)
end
# @param [Object] msg
def sys_abort(msg)
abort(msg)
end
# Print specified line on the same string
#
# @param [String] log_string
def print_in_same_line(log_string)
print "#{log_string}\r"
end
# Print long line with spaces on same line to clear prev message
def print_empty_line
print_in_same_line(" ")
end
# Returns GitHub token. First try to use variable, provided by --token option,
# otherwise try to fetch it from CHANGELOG_GITHUB_TOKEN env variable.
#
# @return [String]
def fetch_github_token
env_var = @options[:token].presence || ENV["CHANGELOG_GITHUB_TOKEN"]
Helper.log.warn NO_TOKEN_PROVIDED unless env_var
env_var
end
# @return [String] helper to return GitHub "user/project"
def user_project
"#{@options[:user]}/#{@options[:project]}"
end
# Returns Hash of all querystring variables in given URI.
#
# @param [String] uri eg. https://api.github.com/repositories/43914960/tags?page=37&foo=1
# @return [Hash] of all GET variables. eg. { 'page' => 37, 'foo' => 1 }
def querystring_as_hash(uri)
Hash[URI.decode_www_form(URI(uri).query || "")]
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/helper.rb | lib/github_changelog_generator/helper.rb | # frozen_string_literal: true
require "logger"
require "rainbow"
module GitHubChangelogGenerator
module Helper
# @return true if the currently running program is a unit test
def self.test?
defined? SpecHelper
end
# :nocov:
@log ||= if test?
Logger.new(nil) # don't show any logs when running tests
else
Logger.new($stdout)
end
@log.formatter = proc do |severity, _datetime, _progname, msg|
string = "#{msg}\n"
case severity
when "DEBUG" then Rainbow(string).magenta
when "INFO" then Rainbow(string).white
when "WARN" then Rainbow(string).yellow
when "ERROR" then Rainbow(string).red
when "FATAL" then Rainbow(string).red.bright
else string
end
end
# :nocov:
# Logging happens using this method
class << self
attr_reader :log
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/argv_parser.rb | lib/github_changelog_generator/argv_parser.rb | # frozen_string_literal: true
require "optparse"
require "github_changelog_generator/version"
module GitHubChangelogGenerator
class ArgvParser
attr_reader :options
def initialize(options = {})
@options = options
end
def parse!(argv)
parser.parse(argv)
rescue OptionParser::ParseError => e
warn [e, parser].join("\n")
Kernel.abort
end
def parser
@parser ||= OptionParser.new do |opts| # rubocop:disable Metrics/BlockLength
opts.banner = "Usage: github_changelog_generator --user USER --project PROJECT [options]"
opts.on("-u", "--user USER", "Username of the owner of the target GitHub repo OR the namespace of target GitHub repo if owned by an organization.") do |last|
options[:user] = last
end
opts.on("-p", "--project PROJECT", "Name of project on GitHub.") do |last|
options[:project] = last
end
opts.on("-t", "--token TOKEN", "To make more than 50 requests per hour your GitHub token is required. You can generate it at: https://github.com/settings/tokens/new") do |last|
options[:token] = last
end
opts.on("-f", "--date-format FORMAT", "Date format. Default is %Y-%m-%d.") do |last|
options[:date_format] = last
end
opts.on("-o", "--output NAME", "Output file. To print to STDOUT instead, use blank as path. Default is CHANGELOG.md") do |last|
options[:output] = last
end
opts.on("-b", "--base NAME", "Optional base file to append generated changes to. Default is HISTORY.md") do |last|
options[:base] = last
end
opts.on("--summary-label LABEL", "Set up custom label for the release summary section. Default is \"\".") do |v|
options[:summary_prefix] = v
end
opts.on("--breaking-label LABEL", "Set up custom label for the breaking changes section. Default is \"**Breaking changes:**\".") do |v|
options[:breaking_prefix] = v
end
opts.on("--enhancement-label LABEL", "Set up custom label for enhancements section. Default is \"**Implemented enhancements:**\".") do |v|
options[:enhancement_prefix] = v
end
opts.on("--bugs-label LABEL", "Set up custom label for bug-fixes section. Default is \"**Fixed bugs:**\".") do |v|
options[:bug_prefix] = v
end
opts.on("--deprecated-label LABEL", "Set up custom label for the deprecated changes section. Default is \"**Deprecated:**\".") do |v|
options[:deprecated_prefix] = v
end
opts.on("--removed-label LABEL", "Set up custom label for the removed changes section. Default is \"**Removed:**\".") do |v|
options[:removed_prefix] = v
end
opts.on("--security-label LABEL", "Set up custom label for the security changes section. Default is \"**Security fixes:**\".") do |v|
options[:security_prefix] = v
end
opts.on("--issues-label LABEL", "Set up custom label for closed-issues section. Default is \"**Closed issues:**\".") do |v|
options[:issue_prefix] = v
end
opts.on("--header-label LABEL", "Set up custom header label. Default is \"# Changelog\".") do |v|
options[:header] = v
end
opts.on("--configure-sections HASH, STRING", "Define your own set of sections which overrides all default sections.") do |v|
options[:configure_sections] = v
end
opts.on("--add-sections HASH, STRING", "Add new sections but keep the default sections.") do |v|
options[:add_sections] = v
end
opts.on("--front-matter JSON", "Add YAML front matter. Formatted as JSON because it's easier to add on the command line.") do |v|
require "yaml"
options[:frontmatter] = "#{JSON.parse(v).to_yaml}---\n"
end
opts.on("--pr-label LABEL", "Set up custom label for pull requests section. Default is \"**Merged pull requests:**\".") do |v|
options[:merge_prefix] = v
end
opts.on("--[no-]issues", "Include closed issues in changelog. Default is true.") do |v|
options[:issues] = v
end
opts.on("--[no-]issues-wo-labels", "Include closed issues without labels in changelog. Default is true.") do |v|
options[:add_issues_wo_labels] = v
end
opts.on("--[no-]pr-wo-labels", "Include pull requests without labels in changelog. Default is true.") do |v|
options[:add_pr_wo_labels] = v
end
opts.on("--[no-]pull-requests", "Include pull-requests in changelog. Default is true.") do |v|
options[:pulls] = v
end
opts.on("--[no-]filter-by-milestone", "Use milestone to detect when issue was resolved. Default is true.") do |last|
options[:filter_issues_by_milestone] = last
end
opts.on("--[no-]issues-of-open-milestones", "Include issues of open milestones. Default is true.") do |v|
options[:issues_of_open_milestones] = v
end
opts.on("--[no-]author", "Add author of pull request at the end. Default is true.") do |author|
options[:author] = author
end
opts.on("--usernames-as-github-logins", "Use GitHub tags instead of Markdown links for the author of an issue or pull-request.") do |v|
options[:usernames_as_github_logins] = v
end
opts.on("--unreleased-only", "Generate log from unreleased closed issues only.") do |v|
options[:unreleased_only] = v
end
opts.on("--[no-]unreleased", "Add to log unreleased closed issues. Default is true.") do |v|
options[:unreleased] = v
end
opts.on("--unreleased-label LABEL", "Set up custom label for unreleased closed issues section. Default is \"**Unreleased:**\".") do |v|
options[:unreleased_label] = v
end
opts.on("--[no-]compare-link", "Include compare link (Full Changelog) between older version and newer version. Default is true.") do |v|
options[:compare_link] = v
end
opts.on("--include-labels x,y,z", Array, "Of the labeled issues, only include the ones with the specified labels.") do |list|
options[:include_labels] = list
end
opts.on("--exclude-labels x,y,z", Array, "Issues with the specified labels will be excluded from changelog. Default is 'duplicate,question,invalid,wontfix'.") do |list|
options[:exclude_labels] = list
end
opts.on("--summary-labels x,y,z", Array, 'Issues with these labels will be added to a new section, called "Release Summary". The section display only body of issues. Default is \'release-summary,summary\'.') do |list|
options[:summary_labels] = list
end
opts.on("--breaking-labels x,y,z", Array, 'Issues with these labels will be added to a new section, called "Breaking changes". Default is \'backwards-incompatible,breaking\'.') do |list|
options[:breaking_labels] = list
end
opts.on("--enhancement-labels x,y,z", Array, 'Issues with the specified labels will be added to "Implemented enhancements" section. Default is \'enhancement,Enhancement\'.') do |list|
options[:enhancement_labels] = list
end
opts.on("--bug-labels x,y,z", Array, 'Issues with the specified labels will be added to "Fixed bugs" section. Default is \'bug,Bug\'.') do |list|
options[:bug_labels] = list
end
opts.on("--deprecated-labels x,y,z", Array, 'Issues with the specified labels will be added to a section called "Deprecated". Default is \'deprecated,Deprecated\'.') do |list|
options[:deprecated_labels] = list
end
opts.on("--removed-labels x,y,z", Array, 'Issues with the specified labels will be added to a section called "Removed". Default is \'removed,Removed\'.') do |list|
options[:removed_labels] = list
end
opts.on("--security-labels x,y,z", Array, 'Issues with the specified labels will be added to a section called "Security fixes". Default is \'security,Security\'.') do |list|
options[:security_labels] = list
end
opts.on("--issue-line-labels x,y,z", Array, 'The specified labels will be shown in brackets next to each matching issue. Use "ALL" to show all labels. Default is [].') do |list|
options[:issue_line_labels] = list
end
opts.on("--include-tags-regex REGEX", "Apply a regular expression on tag names so that they can be included, for example: --include-tags-regex \".*\+\d{1,}\".") do |last|
options[:include_tags_regex] = last
end
opts.on("--exclude-tags x,y,z", Array, "Changelog will exclude specified tags") do |list|
options[:exclude_tags] = list
end
opts.on("--exclude-tags-regex REGEX", "Apply a regular expression on tag names so that they can be excluded, for example: --exclude-tags-regex \".*\+\d{1,}\".") do |last|
options[:exclude_tags_regex] = last
end
opts.on("--since-tag x", "Changelog will start after specified tag.") do |v|
options[:since_tag] = v
end
opts.on("--due-tag x", "Changelog will end before specified tag.") do |v|
options[:due_tag] = v
end
opts.on("--since-commit x", "Fetch only commits after this time. eg. \"2017-01-01 10:00:00\"") do |v|
options[:since_commit] = v
end
opts.on("--max-issues NUMBER", Integer, "Maximum number of issues to fetch from GitHub. Default is unlimited.") do |max|
options[:max_issues] = max
end
opts.on("--release-url URL", "The URL to point to for release links, in printf format (with the tag as variable).") do |url|
options[:release_url] = url
end
opts.on("--github-site URL", "The Enterprise GitHub site where your project is hosted.") do |last|
options[:github_site] = last
end
opts.on("--github-api URL", "The enterprise endpoint to use for your GitHub API.") do |last|
options[:github_endpoint] = last
end
opts.on("--simple-list", "Create a simple list from issues and pull requests. Default is false.") do |v|
options[:simple_list] = v
end
opts.on("--future-release RELEASE-VERSION", "Put the unreleased changes in the specified release number.") do |future_release|
options[:future_release] = future_release
end
opts.on("--release-branch RELEASE-BRANCH", "Limit pull requests to the release branch, such as master or release.") do |release_branch|
options[:release_branch] = release_branch
end
opts.on("--[no-]http-cache", "Use HTTP Cache to cache GitHub API requests (useful for large repos). Default is true.") do |http_cache|
options[:http_cache] = http_cache
end
opts.on("--cache-file CACHE-FILE", "Filename to use for cache. Default is github-changelog-http-cache in a temporary directory.") do |cache_file|
options[:cache_file] = cache_file
end
opts.on("--cache-log CACHE-LOG", "Filename to use for cache log. Default is github-changelog-logger.log in a temporary directory.") do |cache_log|
options[:cache_log] = cache_log
end
opts.on("--config-file CONFIG-FILE", "Path to configuration file. Default is .github_changelog_generator.") do |config_file|
options[:config_file] = config_file
end
opts.on("--ssl-ca-file PATH", "Path to cacert.pem file. Default is a bundled lib/github_changelog_generator/ssl_certs/cacert.pem. Respects SSL_CA_PATH.") do |ssl_ca_file|
options[:ssl_ca_file] = ssl_ca_file
end
opts.on("--require x,y,z", Array, "Path to Ruby file(s) to require before generating changelog.") do |paths|
options[:require] = paths
end
opts.on("--[no-]verbose", "Run verbosely. Default is true.") do |v|
options[:verbose] = v
end
opts.on("-v", "--version", "Print version number.") do |_v|
puts "Version: #{GitHubChangelogGenerator::VERSION}"
exit
end
opts.on("-h", "--help", "Displays Help.") do
puts opts
exit
end
end
end
class << self
def banner
new.parser.banner
end
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/entry.rb | lib/github_changelog_generator/generator/entry.rb | # frozen_string_literal: true
require "github_changelog_generator/generator/section"
module GitHubChangelogGenerator
# This class generates the content for a single changelog entry. An entry is
# generally either for a specific tagged release or the collection of
# unreleased changes.
#
# An entry is comprised of header text followed by a series of sections
# relating to the entry.
#
# @see GitHubChangelogGenerator::Generator
# @see GitHubChangelogGenerator::Section
class Entry
attr_reader :content
def initialize(options = Options.new({}))
@content = ""
@options = Options.new(options)
end
# Generates log entry with header and body
#
# @param [Array] pull_requests List or PR's in new section
# @param [Array] issues List of issues in new section
# @param [String] newer_tag_name Name of the newer tag. Could be nil for `Unreleased` section.
# @param [String] newer_tag_link Name of the newer tag. Could be "HEAD" for `Unreleased` section.
# @param [Time] newer_tag_time Time of the newer tag
# @param [Hash, nil] older_tag_name Older tag, used for the links. Could be nil for last tag.
# @return [String] Ready and parsed section content.
def generate_entry_for_tag(pull_requests, issues, newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name) # rubocop:disable Metrics/ParameterLists
github_site = @options[:github_site] || "https://github.com"
project_url = "#{github_site}/#{@options[:user]}/#{@options[:project]}"
create_sections
@content = generate_header(newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name, project_url)
@content += generate_body(pull_requests, issues)
@content
end
def line_labels_for(issue)
labels = if @options[:issue_line_labels] == ["ALL"]
issue["labels"]
else
issue["labels"].select { |label| @options[:issue_line_labels].include?(label["name"]) }
end
labels.map { |label| " \[[#{label['name']}](#{label['url'].sub('api.github.com/repos', 'github.com')})\]" }.join("")
end
private
# Creates section objects for this entry.
# @return [Nil]
def create_sections
@sections = if @options.configure_sections?
parse_sections(@options[:configure_sections])
elsif @options.add_sections?
default_sections.concat parse_sections(@options[:add_sections])
else
default_sections
end
nil
end
# Turns the argument from the commandline of --configure-sections or
# --add-sections into an array of Section objects.
#
# @param [String, Hash] sections_desc Either string or hash describing sections
# @return [Array] Parsed section objects.
def parse_sections(sections_desc)
require "json"
sections_desc = sections_desc.to_json if sections_desc.instance_of?(Hash)
begin
sections_json = JSON.parse(sections_desc)
rescue JSON::ParserError => e
raise "There was a problem parsing your JSON string for sections: #{e}"
end
sections_json.collect do |name, v|
Section.new(name: name.to_s, prefix: v["prefix"], labels: v["labels"], body_only: v["body_only"], options: @options)
end
end
# Generates header text for an entry.
#
# @param [String] newer_tag_name The name of a newer tag
# @param [String] newer_tag_link Used for URL generation. Could be same as #newer_tag_name or some specific value, like HEAD
# @param [Time] newer_tag_time Time when the newer tag was created
# @param [String] older_tag_name The name of an older tag; used for URLs.
# @param [String] project_url URL for the current project.
# @return [String] Header text content.
def generate_header(newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name, project_url)
header = ""
# Generate date string:
time_string = newer_tag_time.strftime(@options[:date_format])
# Generate tag name and link
release_url = if @options[:release_url]
format(@options[:release_url], newer_tag_link)
else
"#{project_url}/tree/#{newer_tag_link}"
end
header += if newer_tag_name.equal?(@options[:unreleased_label])
"## [#{newer_tag_name}](#{release_url})\n\n"
else
"## [#{newer_tag_name}](#{release_url}) (#{time_string})\n\n"
end
if @options[:compare_link] && older_tag_name
# Generate compare link
header += "[Full Changelog](#{project_url}/compare/#{older_tag_name}...#{newer_tag_link})\n\n"
end
header
end
# Generates complete body text for a tag (without a header)
#
# @param [Array] pull_requests
# @param [Array] issues
# @return [String] Content generated from sections of sorted issues & PRs.
def generate_body(pull_requests, issues)
sort_into_sections(pull_requests, issues)
@sections.map(&:generate_content).join
end
# Default sections to used when --configure-sections is not set.
#
# @return [Array] Section objects.
def default_sections
[
Section.new(name: "summary", prefix: @options[:summary_prefix], labels: @options[:summary_labels], options: @options, body_only: true),
Section.new(name: "breaking", prefix: @options[:breaking_prefix], labels: @options[:breaking_labels], options: @options),
Section.new(name: "enhancements", prefix: @options[:enhancement_prefix], labels: @options[:enhancement_labels], options: @options),
Section.new(name: "bugs", prefix: @options[:bug_prefix], labels: @options[:bug_labels], options: @options),
Section.new(name: "deprecated", prefix: @options[:deprecated_prefix], labels: @options[:deprecated_labels], options: @options),
Section.new(name: "removed", prefix: @options[:removed_prefix], labels: @options[:removed_labels], options: @options),
Section.new(name: "security", prefix: @options[:security_prefix], labels: @options[:security_labels], options: @options)
]
end
# Sorts issues and PRs into entry sections by labels and lack of labels.
#
# @param [Array] pull_requests
# @param [Array] issues
# @return [Nil]
def sort_into_sections(pull_requests, issues)
if @options[:issues]
unmapped_issues = sort_labeled_issues(issues)
add_unmapped_section(unmapped_issues)
end
if @options[:pulls]
unmapped_pull_requests = sort_labeled_issues(pull_requests)
add_unmapped_section(unmapped_pull_requests)
end
nil
end
# Iterates through sections and sorts labeled issues into them based on
# the label mapping. Returns any unmapped or unlabeled issues.
#
# @param [Array] issues Issues or pull requests.
# @return [Array] Issues that were not mapped into any sections.
def sort_labeled_issues(issues)
sorted_issues = []
issues.each do |issue|
label_names = issue["labels"].collect { |l| l["name"] }
# Add PRs in the order of the @sections array. This will either be the
# default sections followed by any --add-sections sections in
# user-defined order, or --configure-sections in user-defined order.
# Ignore the order of the issue labels from github which cannot be
# controlled by the user.
@sections.each do |section|
unless (section.labels & label_names).empty?
section.issues << issue
sorted_issues << issue
break
end
end
end
issues - sorted_issues
end
# Creates a section for issues/PRs with no labels or no mapped labels.
#
# @param [Array] issues
# @return [Nil]
def add_unmapped_section(issues)
unless issues.empty?
# Distinguish between issues and pull requests
if issues.first.key?("pull_request")
name = "merged"
prefix = @options[:merge_prefix]
add_wo_labels = @options[:add_pr_wo_labels]
else
name = "issues"
prefix = @options[:issue_prefix]
add_wo_labels = @options[:add_issues_wo_labels]
end
add_issues = if add_wo_labels
issues
else
# Only add unmapped issues
issues.select { |issue| issue["labels"].any? }
end
merged = Section.new(name: name, prefix: prefix, labels: [], issues: add_issues, options: @options) unless add_issues.empty?
@sections << merged
end
nil
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/generator_processor.rb | lib/github_changelog_generator/generator/generator_processor.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
class Generator
# delete all issues with labels from options[:exclude_labels] array
# @param [Array] issues
# @return [Array] filtered array
def exclude_issues_by_labels(issues)
return issues if !options[:exclude_labels] || options[:exclude_labels].empty?
issues.reject do |issue|
labels = issue["labels"].map { |l| l["name"] }
(labels & options[:exclude_labels]).any?
end
end
# Only include issues without labels if options[:add_issues_wo_labels]
# @param [Array] issues
# @return [Array] filtered array
def exclude_issues_without_labels(issues)
return issues if issues.empty?
return issues if issues.first.key?("pull_request") && options[:add_pr_wo_labels]
return issues if !issues.first.key?("pull_request") && options[:add_issues_wo_labels]
issues.reject do |issue|
issue["labels"].empty?
end
end
# @return [Array] filtered issues accourding milestone
def filter_by_milestone(filtered_issues, tag_name, all_issues)
remove_issues_in_milestones(filtered_issues)
unless tag_name.nil?
# add missed issues (according milestones)
issues_to_add = find_issues_to_add(all_issues, tag_name)
filtered_issues |= issues_to_add
end
filtered_issues
end
# Add all issues, that should be in that tag, according milestone
#
# @param [Array] all_issues
# @param [String] tag_name
# @return [Array] issues with milestone #tag_name
def find_issues_to_add(all_issues, tag_name)
all_issues.select do |issue|
if (milestone = issue["milestone"]).nil?
false
# check, that this milestone in tag list:
elsif (tag = find_tag_for_milestone(milestone)).nil?
false
else
tag["name"] == tag_name
end
end
end
# @return [Array] array with removed issues, that contain milestones with same name as a tag
def remove_issues_in_milestones(filtered_issues)
filtered_issues.select! do |issue|
# leave issues without milestones
if (milestone = issue["milestone"]).nil?
true
# remove issues of open milestones if option is set
elsif milestone["state"] == "open"
@options[:issues_of_open_milestones]
else
# check, that this milestone in tag list:
find_tag_for_milestone(milestone).nil?
end
end
end
def find_tag_for_milestone(milestone)
@filtered_tags.find { |tag| tag["name"] == milestone["title"] }
end
# Method filter issues, that belong only specified tag range
#
# @param [Array] issues issues to filter
# @param [Hash, Nil] newer_tag Tag to find PRs of. May be nil for unreleased section
# @return [Array] filtered issues
def filter_by_tag(issues, newer_tag = nil)
issues.select do |issue|
issue["first_occurring_tag"] == (newer_tag.nil? ? nil : newer_tag["name"])
end
end
# Method filter issues, that belong only specified tag range
# @param [Array] issues issues to filter
# @param [Symbol] hash_key key of date value default is :actual_date
# @param [Hash, Nil] older_tag all issues before this tag date will be excluded. May be nil, if it's first tag
# @param [Hash, Nil] newer_tag all issue after this tag will be excluded. May be nil for unreleased section
# @return [Array] filtered issues
def delete_by_time(issues, hash_key = "actual_date", older_tag = nil, newer_tag = nil)
# in case if not tags specified - return unchanged array
return issues if older_tag.nil? && newer_tag.nil?
older_tag = ensure_older_tag(older_tag, newer_tag)
newer_tag_time = newer_tag && get_time_of_tag(newer_tag)
older_tag_time = older_tag && get_time_of_tag(older_tag)
issues.select do |issue|
if issue[hash_key]
time = Time.parse(issue[hash_key].to_s).utc
tag_in_range_old = tag_newer_old_tag?(older_tag_time, time)
tag_in_range_new = tag_older_new_tag?(newer_tag_time, time)
tag_in_range = tag_in_range_old && tag_in_range_new
tag_in_range
else
false
end
end
end
def ensure_older_tag(older_tag, newer_tag)
return older_tag if older_tag
idx = sorted_tags.index { |t| t["name"] == newer_tag["name"] }
# skip if we are already at the oldest element
return if idx == sorted_tags.size - 1
sorted_tags[idx - 1]
end
def tag_older_new_tag?(newer_tag_time, time)
newer_tag_time.nil? || time <= newer_tag_time
end
def tag_newer_old_tag?(older_tag_time, time)
older_tag_time.nil? || time > older_tag_time
end
# Include issues with labels, specified in :include_labels
# @param [Array] issues to filter
# @return [Array] filtered array of issues
def include_issues_by_labels(issues)
filtered_issues = filter_by_include_labels(issues)
filter_wo_labels(filtered_issues)
end
# @param [Array] items Issues & PRs to filter when without labels
# @return [Array] Issues & PRs without labels or empty array if
# add_issues_wo_labels or add_pr_wo_labels are false
def filter_wo_labels(items)
if items.any? && items.first.key?("pull_request")
return items if options[:add_pr_wo_labels]
elsif options[:add_issues_wo_labels]
return items
end
# The default is to filter items without labels
items.select { |item| item["labels"].map { |l| l["name"] }.any? }
end
# @todo Document this
# @param [Object] issues
def filter_by_include_labels(issues)
if options[:include_labels].nil?
issues
else
issues.select do |issue|
labels = issue["labels"].map { |l| l["name"] } & options[:include_labels]
labels.any? || issue["labels"].empty?
end
end
end
# General filtered function
#
# @param [Array] all_issues PRs or issues
# @return [Array] filtered issues
def filter_array_by_labels(all_issues)
filtered_issues = include_issues_by_labels(all_issues)
filtered_issues = exclude_issues_by_labels(filtered_issues)
exclude_issues_without_labels(filtered_issues)
end
# Filter issues according labels
# @return [Array] Filtered issues
def get_filtered_issues(issues)
issues = filter_array_by_labels(issues)
puts "Filtered issues: #{issues.count}" if options[:verbose]
issues
end
# This method fetches missing params for PR and filter them by specified options
# It include add all PR's with labels from options[:include_labels] array
# And exclude all from :exclude_labels array.
# @return [Array] filtered PR's
def get_filtered_pull_requests(pull_requests)
pull_requests = filter_array_by_labels(pull_requests)
pull_requests = filter_merged_pull_requests(pull_requests)
puts "Filtered pull requests: #{pull_requests.count}" if options[:verbose]
pull_requests
end
# This method filter only merged PR and
# fetch missing required attributes for pull requests
# :merged_at - is a date, when issue PR was merged.
# More correct to use merged date, rather than closed date.
def filter_merged_pull_requests(pull_requests)
print "Fetching merged dates...\r" if options[:verbose]
closed_pull_requests = @fetcher.fetch_closed_pull_requests
pull_requests.each do |pr|
fetched_pr = closed_pull_requests.find do |fpr|
fpr["number"] == pr["number"]
end
if fetched_pr
pr["merged_at"] = fetched_pr["merged_at"]
closed_pull_requests.delete(fetched_pr)
end
end
pull_requests.reject! do |pr|
pr["merged_at"].nil?
end
pull_requests
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/section.rb | lib/github_changelog_generator/generator/section.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
# This class generates the content for a single section of a changelog entry.
# It turns the tagged issues and PRs into a well-formatted list of changes to
# be later incorporated into a changelog entry.
#
# @see GitHubChangelogGenerator::Entry
class Section
# @return [String]
attr_accessor :name
# @return [String] a merge prefix, or an issue prefix
attr_reader :prefix
# @return [Array<Hash>]
attr_reader :issues
# @return [Array<String>]
attr_reader :labels
# @return [Boolean]
attr_reader :body_only
# @return [Options]
attr_reader :options
def initialize(opts = {})
@name = opts[:name]
@prefix = opts[:prefix]
@labels = opts[:labels] || []
@issues = opts[:issues] || []
@options = opts[:options] || Options.new({})
@body_only = opts[:body_only] || false
@entry = Entry.new(options)
end
# Returns the content of a section.
#
# @return [String] Generated section content
def generate_content
content = +""
if @issues.any?
content += "#{@prefix}\n\n" unless @options[:simple_list] || @prefix.blank?
@issues.each do |issue|
merge_string = get_string_for_issue(issue)
content += "- " unless @body_only
content += "#{merge_string}\n"
end
content += "\n"
end
content
end
private
# Parse issue and generate single line formatted issue line.
#
# Example output:
# - Add coveralls integration [\#223](https://github.com/github-changelog-generator/github-changelog-generator/pull/223) (@github-changelog-generator)
#
# @param [Hash] issue Fetched issue from GitHub
# @return [String] Markdown-formatted single issue
def get_string_for_issue(issue)
encapsulated_title = encapsulate_string issue["title"]
title_with_number = "#{encapsulated_title} [\\##{issue['number']}](#{issue['html_url']})"
title_with_number = "#{title_with_number}#{@entry.line_labels_for(issue)}" if @options[:issue_line_labels].present?
line = issue_line_with_user(title_with_number, issue)
issue_line_with_body(line, issue)
end
def issue_line_with_body(line, issue)
return normalize_body(issue["body"]) if @body_only && issue["body"].present?
return line if !@options[:issue_line_body] || issue["body"].blank?
# get issue body till first line break
body_paragraph = body_till_first_break(normalize_body(issue["body"]))
# remove spaces from beginning of the string
body_paragraph.rstrip!
# encapsulate to md
encapsulated_body = " \n#{encapsulate_string(body_paragraph)}"
"**#{line}** #{encapsulated_body}"
end
# Normalize line endings from CRLF to LF
def normalize_body(body)
body.gsub(/\r?\n/, "\n")
end
def body_till_first_break(body)
body.split(/\n/, 2).first
end
def issue_line_with_user(line, issue)
return line if !@options[:author] || issue["pull_request"].nil?
user = issue["user"]
return "#{line} ({Null user})" unless user
if @options[:usernames_as_github_logins]
"#{line} (@#{user['login']})"
else
"#{line} ([#{user['login']}](#{user['html_url']}))"
end
end
ENCAPSULATED_CHARACTERS = %w(< > * _ \( \) [ ] #)
# Encapsulate characters to make Markdown look as expected.
#
# @param [String] string
# @return [String] encapsulated input string
def encapsulate_string(string)
string = string.gsub("\\", "\\\\")
ENCAPSULATED_CHARACTERS.each do |char|
# Only replace char with escaped version if it isn't inside backticks (markdown inline code).
# This relies on each opening '`' being closed (ie an even number in total).
# A char is *outside* backticks if there is an even number of backticks following it.
string = string.gsub(%r{#{Regexp.escape(char)}(?=([^`]*`[^`]*`)*[^`]*$)}, "\\#{char}")
end
string
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/generator_tags.rb | lib/github_changelog_generator/generator/generator_tags.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
class Generator
# fetch, filter tags, fetch dates and sort them in time order
def fetch_and_filter_tags
since_tag
due_tag
all_tags = @fetcher.fetch_all_tags
fetch_tags_dates(all_tags) # Creates a Hash @tag_times_hash
all_sorted_tags = sort_tags_by_date(all_tags)
@sorted_tags = filter_included_tags(all_sorted_tags)
@sorted_tags = filter_excluded_tags(@sorted_tags)
@filtered_tags = get_filtered_tags(@sorted_tags)
@tag_section_mapping = build_tag_section_mapping(@filtered_tags, @filtered_tags)
@filtered_tags
end
# @param [Array] section_tags are the tags that need a subsection output
# @param [Array] filtered_tags is the list of filtered tags ordered from newest -> oldest
# @return [Hash] key is the tag to output, value is an array of [Left Tag, Right Tag]
# PRs to include in this section will be >= [Left Tag Date] and <= [Right Tag Date]
# rubocop:disable Style/For - for allows us to be more concise
def build_tag_section_mapping(section_tags, filtered_tags)
tag_mapping = {}
for i in 0..(section_tags.length - 1)
tag = section_tags[i]
# Don't create section header for the "since" tag
next if since_tag && tag["name"] == since_tag
# Don't create a section header for the first tag in between_tags
next if options[:between_tags] && tag == section_tags.last
# Don't create a section header for excluded tags
next unless filtered_tags.include?(tag)
older_tag = section_tags[i + 1]
tag_mapping[tag] = [older_tag, tag]
end
tag_mapping
end
# rubocop:enable Style/For
# Sort all tags by date, newest to oldest
def sort_tags_by_date(tags)
puts "Sorting tags..." if options[:verbose]
tags.sort_by! do |x|
get_time_of_tag(x)
end.reverse!
end
# Returns date for given GitHub Tag hash
#
# Memoize the date by tag name.
#
# @param [Hash] tag_name
#
# @return [Time] time of specified tag
def get_time_of_tag(tag_name)
raise ChangelogGeneratorError, "tag_name is nil" if tag_name.nil?
name_of_tag = tag_name.fetch("name")
time_for_tag_name = @tag_times_hash[name_of_tag]
return time_for_tag_name if time_for_tag_name
@fetcher.fetch_date_of_tag(tag_name).tap do |time_string|
@tag_times_hash[name_of_tag] = time_string
end
end
# Detect link, name and time for specified tag.
#
# @param [Hash] newer_tag newer tag. Can be nil, if it's Unreleased section.
# @return [Array] link, name and time of the tag
def detect_link_tag_time(newer_tag)
# if tag is nil - set current time
newer_tag_time = newer_tag.nil? ? Time.new.getutc : get_time_of_tag(newer_tag)
# if it's future release tag - set this value
if newer_tag.nil? && options[:future_release]
newer_tag_name = options[:future_release]
newer_tag_link = options[:future_release]
else
# put unreleased label if there is no name for the tag
newer_tag_name = newer_tag.nil? ? options[:unreleased_label] : newer_tag["name"]
newer_tag_link = newer_tag.nil? ? "HEAD" : newer_tag_name
end
[newer_tag_link, newer_tag_name, newer_tag_time]
end
# @return [Object] try to find newest tag using #Reader and :base option if specified otherwise returns nil
def since_tag
@since_tag ||= options.fetch(:since_tag) { version_of_first_item }
end
def due_tag
@due_tag ||= options.fetch(:due_tag, nil)
end
def version_of_first_item
return unless File.file?(options[:base].to_s)
sections = GitHubChangelogGenerator::Reader.new.read(options[:base])
sections.first["version"] if sections && sections.any?
end
# Return tags after filtering tags in lists provided by option: --exclude-tags
#
# @return [Array]
def get_filtered_tags(all_tags)
filtered_tags = filter_since_tag(all_tags)
filter_due_tag(filtered_tags)
end
# @param [Array] all_tags all tags
# @return [Array] filtered tags according :since_tag option
def filter_since_tag(all_tags)
return all_tags unless (tag = since_tag)
raise ChangelogGeneratorError, "Error: can't find tag #{tag}, specified with --since-tag option." if all_tags.none? { |t| t["name"] == tag }
if (idx = all_tags.index { |t| t["name"] == tag })
all_tags[0..idx]
else
[]
end
end
# @param [Array] all_tags all tags
# @return [Array] filtered tags according :due_tag option
def filter_due_tag(all_tags)
return all_tags unless (tag = due_tag)
raise ChangelogGeneratorError, "Error: can't find tag #{tag}, specified with --due-tag option." if all_tags.none? { |t| t["name"] == tag }
if (idx = all_tags.index { |t| t["name"] == tag }) > 0
all_tags[(idx + 1)..]
else
[]
end
end
# @param [Array] all_tags all tags
# @return [Array] filtered tags according to :include_tags_regex option
def filter_included_tags(all_tags)
if options[:include_tags_regex]
regex = Regexp.new(options[:include_tags_regex])
all_tags.select { |tag| regex =~ tag["name"] }
else
all_tags
end
end
# @param [Array] all_tags all tags
# @return [Array] filtered tags according :exclude_tags or :exclude_tags_regex option
def filter_excluded_tags(all_tags)
if options[:exclude_tags]
apply_exclude_tags(all_tags)
elsif options[:exclude_tags_regex]
apply_exclude_tags_regex(all_tags)
else
all_tags
end
end
private
def apply_exclude_tags(all_tags)
if options[:exclude_tags].is_a?(Regexp)
filter_tags_with_regex(all_tags, options[:exclude_tags], "--exclude-tags")
else
filter_exact_tags(all_tags)
end
end
def apply_exclude_tags_regex(all_tags)
regex = Regexp.new(options[:exclude_tags_regex])
filter_tags_with_regex(all_tags, regex, "--exclude-tags-regex")
end
def filter_tags_with_regex(all_tags, regex, regex_option_name)
warn_if_nonmatching_regex(all_tags, regex, regex_option_name)
all_tags.reject { |tag| regex =~ tag["name"] }
end
def filter_exact_tags(all_tags)
options[:exclude_tags].each do |tag|
warn_if_tag_not_found(all_tags, tag)
end
all_tags.reject { |tag| options[:exclude_tags].include?(tag["name"]) }
end
def warn_if_nonmatching_regex(all_tags, regex, regex_option_name)
return if all_tags.any? { |t| regex.match?(t["name"]) }
Helper.log.warn "Warning: unable to reject any tag, using regex "\
"#{regex.inspect} in #{regex_option_name} option."
end
def warn_if_tag_not_found(all_tags, tag)
return if all_tags.any? { |t| t["name"] == tag }
Helper.log.warn("Warning: can't find tag #{tag}, specified with --exclude-tags option.")
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/generator.rb | lib/github_changelog_generator/generator/generator.rb | # frozen_string_literal: true
require "github_changelog_generator/octo_fetcher"
require "github_changelog_generator/generator/generator_fetcher"
require "github_changelog_generator/generator/generator_processor"
require "github_changelog_generator/generator/generator_tags"
require "github_changelog_generator/generator/entry"
require "github_changelog_generator/generator/section"
module GitHubChangelogGenerator
# Default error for ChangelogGenerator
class ChangelogGeneratorError < StandardError
end
# This class is the high-level code for gathering issues and PRs for a github
# repository and generating a CHANGELOG.md file. A changelog is made up of a
# series of "entries" of all tagged releases, plus an extra entry for the
# unreleased changes. Entries are made up of various organizational
# "sections," and sections contain the github issues and PRs.
#
# So the changelog contains entries, entries contain sections, and sections
# contain issues and PRs.
#
# @see GitHubChangelogGenerator::Entry
# @see GitHubChangelogGenerator::Section
class Generator
attr_accessor :options, :filtered_tags, :tag_section_mapping, :sorted_tags
CREDIT_LINE = <<~CREDIT
\\* *This Changelog was automatically generated \
by [github_changelog_generator]\
(https://github.com/github-changelog-generator/github-changelog-generator)*
CREDIT
# A Generator responsible for all logic, related with changelog generation from ready-to-parse issues
#
# Example:
# generator = GitHubChangelogGenerator::Generator.new
# content = generator.compound_changelog
def initialize(options = {})
@options = options
@tag_times_hash = {}
@fetcher = GitHubChangelogGenerator::OctoFetcher.new(options)
@sections = []
end
# Main function to start changelog generation
#
# @return [String] Generated changelog file
def compound_changelog
@options.load_custom_ruby_files
Sync do
fetch_and_filter_tags
fetch_issues_and_pr
log = if @options[:unreleased_only]
generate_entry_between_tags(@filtered_tags[0], nil)
else
generate_entries_for_all_tags
end
log += File.read(@options[:base]) if File.file?(@options[:base])
log = remove_old_fixed_string(log)
log = insert_fixed_string(log)
@log = log
end
end
private
# Generate log only between 2 specified tags
# @param [String] older_tag all issues before this tag date will be excluded. May be nil, if it's first tag
# @param [String] newer_tag all issue after this tag will be excluded. May be nil for unreleased section
def generate_entry_between_tags(older_tag, newer_tag)
filtered_issues, filtered_pull_requests = filter_issues_for_tags(newer_tag, older_tag)
if newer_tag.nil? && filtered_issues.empty? && filtered_pull_requests.empty?
# do not generate empty unreleased section
return +""
end
newer_tag_link, newer_tag_name, newer_tag_time = detect_link_tag_time(newer_tag)
# If the older tag is nil, go back in time from the latest tag and find
# the SHA for the first commit.
older_tag_name =
if older_tag.nil?
@fetcher.oldest_commit["sha"]
else
older_tag["name"]
end
Entry.new(options).generate_entry_for_tag(filtered_pull_requests, filtered_issues, newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name)
end
# Filters issues and pull requests based on, respectively, `actual_date`
# and `merged_at` timestamp fields. `actual_date` is the detected form of
# `closed_at` based on merge event SHA commit times.
#
# @return [Array] filtered issues and pull requests
def filter_issues_for_tags(newer_tag, older_tag)
filtered_pull_requests = filter_by_tag(@pull_requests, newer_tag)
filtered_issues = delete_by_time(@issues, "actual_date", older_tag, newer_tag)
newer_tag_name = newer_tag.nil? ? nil : newer_tag["name"]
if options[:filter_issues_by_milestone]
# delete excess irrelevant issues (according milestones). Issue #22.
filtered_issues = filter_by_milestone(filtered_issues, newer_tag_name, @issues)
filtered_pull_requests = filter_by_milestone(filtered_pull_requests, newer_tag_name, @pull_requests)
end
[filtered_issues, filtered_pull_requests]
end
# The full cycle of generation for whole project
# @return [String] All entries in the changelog
def generate_entries_for_all_tags
puts "Generating entry..." if options[:verbose]
entries = generate_unreleased_entry
@tag_section_mapping.each_pair do |_tag_section, left_right_tags|
older_tag, newer_tag = left_right_tags
entries += generate_entry_between_tags(older_tag, newer_tag)
end
entries
end
def generate_unreleased_entry
entry = +""
if options[:unreleased]
start_tag = @filtered_tags[0] || @sorted_tags.last
unreleased_entry = generate_entry_between_tags(start_tag, nil)
entry += unreleased_entry if unreleased_entry
end
entry
end
# Fetches @pull_requests and @issues and filters them based on options.
#
# @return [Nil] No return.
def fetch_issues_and_pr
issues, pull_requests = @fetcher.fetch_closed_issues_and_pr
@pull_requests = options[:pulls] ? get_filtered_pull_requests(pull_requests) : []
@issues = options[:issues] ? get_filtered_issues(issues) : []
fetch_events_for_issues_and_pr
detect_actual_closed_dates(@issues + @pull_requests)
prs_left = add_first_occurring_tag_to_prs(@sorted_tags, @pull_requests)
# PRs in prs_left will be untagged, not in release branch, and not
# rebased. They should not be included in the changelog as they probably
# have been merged to a branch other than the release branch.
@pull_requests -= prs_left
nil
end
# Remove the previously assigned fixed message.
# @param log [String] Old lines are fixed
def remove_old_fixed_string(log)
log.gsub!(/#{Regexp.escape(@options[:frontmatter])}/, "") if @options[:frontmatter]
log.gsub!(/#{Regexp.escape(@options[:header])}\n{,2}/, "")
log.gsub!(/\n{,2}#{Regexp.escape(CREDIT_LINE)}/, "") # Remove old credit lines
log
end
# Add template messages to given string. Previously added
# messages of the same wording are removed.
# @param log [String]
def insert_fixed_string(log)
ins = +""
ins += @options[:frontmatter] if @options[:frontmatter]
ins += "#{@options[:header]}\n\n"
log.insert(0, ins)
log += "\n\n#{CREDIT_LINE}"
log
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
github-changelog-generator/github-changelog-generator | https://github.com/github-changelog-generator/github-changelog-generator/blob/df6622dbdc907e7c3a4f851383a47c47715393b2/lib/github_changelog_generator/generator/generator_fetcher.rb | lib/github_changelog_generator/generator/generator_fetcher.rb | # frozen_string_literal: true
module GitHubChangelogGenerator
class Generator
# Fetch event for issues and pull requests
# @return [Array] array of fetched issues
def fetch_events_for_issues_and_pr
print "Fetching events for issues and PR: 0/#{@issues.count + @pull_requests.count}\r" if options[:verbose]
# Async fetching events:
@fetcher.fetch_events_async(@issues + @pull_requests)
end
# Async fetching of all tags dates
def fetch_tags_dates(tags)
print "Fetching tag dates...\r" if options[:verbose]
i = 0
tags.each do |tag|
get_time_of_tag(tag)
i += 1
end
puts "Fetching tags dates: #{i}/#{tags.count}" if options[:verbose]
end
# Find correct closed dates, if issues was closed by commits
def detect_actual_closed_dates(issues)
print "Fetching closed dates for issues...\r" if options[:verbose]
i = 0
issues.each do |issue|
find_closed_date_by_commit(issue)
i += 1
end
puts "Fetching closed dates for issues: #{i}/#{issues.count}" if options[:verbose]
end
# Adds a key "first_occurring_tag" to each PR with a value of the oldest
# tag that a PR's merge commit occurs in in the git history. This should
# indicate the release of each PR by git's history regardless of dates and
# divergent branches.
#
# @param [Array] tags The tags sorted by time, newest to oldest.
# @param [Array] prs The PRs to discover the tags of.
# @return [Nil] No return; PRs are updated in-place.
def add_first_occurring_tag_to_prs(tags, prs)
total = prs.count
prs_left = associate_tagged_prs(tags, prs, total)
prs_left = associate_release_branch_prs(prs_left, total)
prs_left = associate_rebase_comment_prs(tags, prs_left, total) if prs_left.any?
Helper.log.info "Associating PRs with tags: #{total}/#{total}"
prs_left
end
# Associate merged PRs by the merge SHA contained in each tag. If the
# merge_commit_sha is not found in any tag's history, skip association.
#
# @param [Array] tags The tags sorted by time, newest to oldest.
# @param [Array] prs The PRs to associate.
# @return [Array] PRs without their merge_commit_sha in a tag.
def associate_tagged_prs(tags, prs, total)
@fetcher.fetch_tag_shas(tags)
i = 0
prs.reject do |pr|
found = false
# XXX Wish I could use merge_commit_sha, but gcg doesn't currently
# fetch that. See
# https://developer.github.com/v3/pulls/#get-a-single-pull-request vs.
# https://developer.github.com/v3/pulls/#list-pull-requests
if pr["events"] && (event = pr["events"].find { |e| e["event"] == "merged" })
# Iterate tags.reverse (oldest to newest) to find first tag of each PR.
if (oldest_tag = tags.reverse.find { |tag| tag["shas_in_tag"].include?(event["commit_id"]) })
pr["first_occurring_tag"] = oldest_tag["name"]
found = true
i += 1
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
end
else
# Either there were no events or no merged event. GitHub's api can be
# weird like that apparently. Check for a rebased comment before erroring.
no_events_pr = associate_rebase_comment_prs(tags, [pr], total)
raise StandardError, "No merge sha found for PR #{pr['number']} via the GitHub API" unless no_events_pr.empty?
found = true
i += 1
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
end
found
end
end
# Associate merged PRs by the HEAD of the release branch. If no
# --release-branch was specified, then the github default branch is used.
#
# @param [Array] prs_left PRs not associated with any tag.
# @param [Integer] total The total number of PRs to associate; used for verbose printing.
# @return [Array] PRs without their merge_commit_sha in the branch.
def associate_release_branch_prs(prs_left, total)
if prs_left.any?
i = total - prs_left.count
prs_left.reject do |pr|
found = false
if pr["events"] && (event = pr["events"].find { |e| e["event"] == "merged" }) && sha_in_release_branch?(event["commit_id"])
found = true
i += 1
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
end
found
end
else
prs_left
end
end
# Associate merged PRs by the SHA detected in github comments of the form
# "rebased commit: <sha>". For use when the merge_commit_sha is not in the
# actual git history due to rebase.
#
# @param [Array] tags The tags sorted by time, newest to oldest.
# @param [Array] prs_left The PRs not yet associated with any tag or branch.
# @return [Array] PRs without rebase comments.
def associate_rebase_comment_prs(tags, prs_left, total)
i = total - prs_left.count
# Any remaining PRs were not found in the list of tags by their merge
# commit and not found in any specified release branch. Fallback to
# rebased commit comment.
@fetcher.fetch_comments_async(prs_left)
prs_left.reject do |pr|
found = false
if pr["comments"] && (rebased_comment = pr["comments"].reverse.find { |c| c["body"].match(%r{rebased commit: ([0-9a-f]{40})}i) })
rebased_sha = rebased_comment["body"].match(%r{rebased commit: ([0-9a-f]{40})}i)[1]
if (oldest_tag = tags.reverse.find { |tag| tag["shas_in_tag"].include?(rebased_sha) })
pr["first_occurring_tag"] = oldest_tag["name"]
found = true
i += 1
elsif sha_in_release_branch?(rebased_sha)
found = true
i += 1
else
raise StandardError, "PR #{pr['number']} has a rebased SHA comment but that SHA was not found in the release branch or any tags"
end
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
else
puts "Warning: PR #{pr['number']} merge commit was not found in the release branch or tagged git history and no rebased SHA comment was found"
end
found
end
end
# Fill :actual_date parameter of specified issue by closed date of the commit, if it was closed by commit.
# @param [Hash] issue
def find_closed_date_by_commit(issue)
return if issue["events"].nil?
# if it's PR -> then find "merged event", in case of usual issue -> found closed date
compare_string = issue["merged_at"].nil? ? "closed" : "merged"
# reverse! - to find latest closed event. (event goes in date order)
issue["events"].reverse!.each do |event|
if event["event"] == compare_string
set_date_from_event(event, issue)
break
end
end
# TODO: assert issues, that remain without 'actual_date' hash for some reason.
end
# Set closed date from this issue
#
# @param [Hash] event
# @param [Hash] issue
def set_date_from_event(event, issue)
if event["commit_id"].nil?
issue["actual_date"] = issue["closed_at"]
return
end
commit = @fetcher.fetch_commit(event["commit_id"])
issue["actual_date"] = commit["commit"]["author"]["date"]
# issue['actual_date'] = commit['author']['date']
rescue StandardError
puts "Warning: Can't fetch commit #{event['commit_id']}. It is probably referenced from another repo."
issue["actual_date"] = issue["closed_at"]
end
private
# Detect if a sha occurs in the --release-branch. Uses the github repo
# default branch if not specified.
#
# @param [String] sha SHA to check.
# @return [Boolean] True if SHA is in the branch git history.
def sha_in_release_branch?(sha)
branch = @options[:release_branch] || @fetcher.default_branch
@fetcher.commits_in_branch(branch).include?(sha)
end
end
end
| ruby | MIT | df6622dbdc907e7c3a4f851383a47c47715393b2 | 2026-01-04T15:39:33.741598Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/simple_form_test.rb | test/simple_form_test.rb | # frozen_string_literal: true
require 'test_helper'
class SimpleFormTest < ActiveSupport::TestCase
test 'setup block yields self' do
SimpleForm.setup do |config|
assert_equal SimpleForm, config
end
end
test 'setup block configure Simple Form' do
SimpleForm.setup do |config|
assert_equal SimpleForm, config
end
assert_equal true, SimpleForm.configured?
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require 'minitest/autorun'
require 'active_model'
require 'action_controller'
require 'action_view'
ActionView::RoutingUrlFor.include ActionDispatch::Routing::UrlFor
require 'action_view/template'
require 'action_view/test_case'
module Rails
def self.env
ActiveSupport::StringInquirer.new("test")
end
end
$:.unshift File.expand_path("../../lib", __FILE__)
require 'simple_form'
require "rails/generators/test_case"
require 'generators/simple_form/install_generator'
Dir["#{File.dirname(__FILE__)}/support/*.rb"].each do |file|
require file unless file.end_with?('discovery_inputs.rb')
end
I18n.default_locale = :en
require 'country_select'
Rails::Dom::Testing::Assertions::SelectorAssertions::HTMLSelector::NO_STRIP << "label"
if ActiveSupport::TestCase.respond_to?(:test_order=)
ActiveSupport::TestCase.test_order = :random
end
require "rails/test_unit/line_filtering"
class ActionView::TestCase
include MiscHelpers
include SimpleForm::ActionViewExtensions::FormHelper
extend Rails::LineFiltering
setup :set_controller
setup :setup_users
def set_controller
@controller = MockController.new
end
def setup_users(extra_attributes = {})
@user = User.build(extra_attributes)
@decorated_user = Decorator.new(@user)
@validating_user = ValidatingUser.build({
name: 'Tester McTesterson',
description: 'A test user of the most distinguished caliber',
home_picture: 'Home picture',
age: 19,
amount: 15,
attempts: 1,
company: [1]
}.merge!(extra_attributes))
@other_validating_user = OtherValidatingUser.build({
age: 19,
company: 1
}.merge!(extra_attributes))
end
def protect_against_forgery?
false
end
def user_path(*args)
'/users'
end
def company_user_path(*args)
'/company/users'
end
alias :users_path :user_path
alias :super_user_path :user_path
alias :validating_user_path :user_path
alias :validating_users_path :user_path
alias :other_validating_user_path :user_path
alias :user_with_attachment_path :user_path
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/support/mock_controller.rb | test/support/mock_controller.rb | # frozen_string_literal: true
class MockController
attr_writer :action_name
def _routes
self
end
def action_name
defined?(@action_name) ? @action_name : "edit"
end
def url_for(*)
"http://example.com"
end
def url_options
{}
end
def polymorphic_mappings(*); {}; end
def hash_for_user_path(*); end
def hash_for_validating_user_path(*); end
def hash_for_other_validating_user_path(*); end
def hash_for_users_path(*); end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/support/misc_helpers.rb | test/support/misc_helpers.rb | # frozen_string_literal: true
module MiscHelpers
def store_translations(locale, translations, &block)
I18n.backend.store_translations locale, translations
yield
ensure
I18n.reload!
I18n.backend.send :init_translations
end
def assert_no_select(selector, value = nil)
assert_select(selector, text: value, count: 0)
end
def swap(object, new_values)
old_values = {}
new_values.each do |key, value|
old_values[key] = object.send key
object.send :"#{key}=", value
end
yield
ensure
old_values.each do |key, value|
object.send :"#{key}=", value
end
end
def stub_any_instance(klass, method, value)
klass.class_eval do
alias_method :"new_#{method}", method
define_method(method) do
if value.respond_to?(:call)
value.call
else
value
end
end
end
yield
ensure
klass.class_eval do
undef_method method
alias_method method, :"new_#{method}"
undef_method :"new_#{method}"
end
end
def swap_wrapper(name = :default, wrapper = custom_wrapper)
old = SimpleForm.wrappers[name.to_s]
SimpleForm.wrappers[name.to_s] = wrapper
yield
ensure
SimpleForm.wrappers[name.to_s] = old
end
def custom_wrapper
SimpleForm.build tag: :section, class: "custom_wrapper", pattern: false do |b|
b.use :pattern
b.wrapper :another, class: "another_wrapper" do |ba|
ba.use :label
ba.use :input
end
b.wrapper :error_wrapper, tag: :div, class: "error_wrapper" do |be|
be.use :error, wrap_with: { tag: :span, class: "omg_error" }
end
b.use :hint, wrap_with: { class: "omg_hint" }
end
end
def custom_wrapper_with_wrapped_optional_component
SimpleForm.build tag: :section, class: "custom_wrapper" do |b|
b.wrapper tag: :div, class: 'no_output_wrapper' do |ba|
ba.optional :hint, wrap_with: { tag: :p, class: 'omg_hint' }
end
end
end
def custom_wrapper_with_unless_blank
SimpleForm.build tag: :section, class: "custom_wrapper" do |b|
b.wrapper tag: :div, class: 'no_output_wrapper', unless_blank: true do |ba|
ba.optional :hint, wrap_with: { tag: :p, class: 'omg_hint' }
end
end
end
def custom_wrapper_with_input_class
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :label
b.use :input, class: 'inline-class'
end
end
def custom_wrapper_with_input_data_modal
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :label
b.use :input, data: { modal: 'data-modal', wrapper: 'data-wrapper' }
end
end
def custom_wrapper_with_input_aria_modal
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :label
b.use :input, aria: { modal: 'aria-modal', wrapper: 'aria-wrapper' }
end
end
def custom_wrapper_with_label_class
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :label, class: 'inline-class'
b.use :input
end
end
def custom_wrapper_with_input_attributes
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :input, data: { modal: true }
end
end
def custom_wrapper_with_label_input_class
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :label_input, class: 'inline-class'
end
end
def custom_wrapper_with_wrapped_input
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.wrapper tag: :div, class: 'elem' do |component|
component.use :label
component.use :input, wrap_with: { tag: :div, class: 'input' }
end
end
end
def custom_wrapper_with_wrapped_label
SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.wrapper tag: :div, class: 'elem' do |component|
component.use :label, wrap_with: { tag: :div, class: 'label' }
component.use :input
end
end
end
def custom_wrapper_without_top_level
SimpleForm.build tag: false, class: 'custom_wrapper_without_top_level' do |b|
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
end
end
def custom_wrapper_without_class
SimpleForm.build tag: :div, wrapper_html: { id: 'custom_wrapper_without_class' } do |b|
b.use :label_input
end
end
def custom_wrapper_with_label_html_option
SimpleForm.build tag: :div, class: "custom_wrapper", label_html: { class: 'extra-label-class' } do |b|
b.use :label_input
end
end
def custom_wrapper_with_wrapped_label_input
SimpleForm.build tag: :section, class: "custom_wrapper", pattern: false do |b|
b.use :label_input, wrap_with: { tag: :div, class: :field }
end
end
def custom_wrapper_with_additional_attributes
SimpleForm.build tag: :div, class: 'custom_wrapper', html: { data: { wrapper: :test }, title: 'some title' } do |b|
b.use :label_input
end
end
def custom_wrapper_with_full_error
SimpleForm.build tag: :div, class: 'custom_wrapper' do |b|
b.use :full_error, wrap_with: { tag: :span, class: :error }
end
end
def custom_wrapper_with_label_text
SimpleForm.build label_text: proc { |label, required| "**#{label}**" } do |b|
b.use :label_input
end
end
def custom_wrapper_with_custom_label_component
SimpleForm.build tag: :span, class: 'custom_wrapper' do |b|
b.use :label_text
end
end
def custom_wrapper_with_html5_components
SimpleForm.build tag: :span, class: 'custom_wrapper' do |b|
b.use :label_text
end
end
def custom_wrapper_with_required_input
SimpleForm.build tag: :span, class: 'custom_wrapper' do |b|
b.use :html5
b.use :input, required: true
end
end
def custom_wrapper_with_input_error_class
SimpleForm.build tag: :div, class: "custom_wrapper", error_class: :field_with_errors do |b|
b.use :label
b.use :input, class: 'inline-class', error_class: 'is-invalid'
end
end
def custom_wrapper_with_input_valid_class(valid_class: :field_without_errors)
SimpleForm.build tag: :div, class: "custom_wrapper", valid_class: valid_class do |b|
b.use :label
b.use :input, class: 'inline-class', valid_class: 'is-valid'
end
end
def custom_form_for(object, *args, &block)
simple_form_for(object, *args, { builder: CustomFormBuilder }, &block)
end
def custom_mapping_form_for(object, *args, &block)
simple_form_for(object, *args, { builder: CustomMapTypeFormBuilder }, &block)
end
def with_concat_form_for(*args, &block)
concat simple_form_for(*args, &(block || proc {}))
end
def with_concat_fields_for(*args, &block)
concat simple_fields_for(*args, &block)
end
def with_concat_custom_form_for(*args, &block)
concat custom_form_for(*args, &block)
end
def with_concat_custom_mapping_form_for(*args, &block)
concat custom_mapping_form_for(*args, &block)
end
def with_form_for(object, *args, &block)
with_concat_form_for(object) do |f|
f.input(*args, &block)
end
end
def with_input_for(object, attribute_name, type, options = {})
with_concat_form_for(object) do |f|
f.input(attribute_name, options.merge(as: type))
end
end
def with_input_field_for(object, *args)
with_concat_form_for(object) do |f|
f.input_field(*args)
end
end
end
class CustomFormBuilder < SimpleForm::FormBuilder
def input(attribute_name, *args, &block)
super(attribute_name, *args, { input_html: { class: 'custom' } }, &block)
end
end
class CustomMapTypeFormBuilder < SimpleForm::FormBuilder
map_type :custom_type, to: SimpleForm::Inputs::StringInput
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/support/models.rb | test/support/models.rb | # frozen_string_literal: true
Association = Struct.new(:klass, :name, :macro, :scope, :options)
Column = Struct.new(:name, :type, :limit) do
end
Relation = Struct.new(:records) do
delegate :each, to: :records
def where(conditions = nil)
self.class.new conditions ? [records.first] : records
end
def order(conditions = nil)
self.class.new conditions ? records.last : records
end
alias_method :to_a, :records
alias_method :to_ary, :records
end
Decorator = Struct.new(:object) do
def to_model
object
end
end
Picture = Struct.new(:id, :name) do
extend ActiveModel::Naming
include ActiveModel::Conversion
def self.where(conditions = nil)
if conditions.is_a?(Hash) && conditions[:name]
all.to_a.last
else
all
end
end
def self.all
Relation.new((1..3).map { |i| new(i, "#{name} #{i}") })
end
end
Company = Struct.new(:id, :name) do
extend ActiveModel::Naming
include ActiveModel::Conversion
class << self
delegate :order, :where, to: :_relation
end
def self._relation
all
end
def self.all
Relation.new((1..3).map { |i| new(i, "#{name} #{i}") })
end
def persisted?
true
end
end
Friend = Struct.new(:id, :name) do
extend ActiveModel::Naming
include ActiveModel::Conversion
def self.all
(1..3).map { |i| new(i, "#{name} #{i}") }
end
def persisted?
true
end
end
class Tag < Company
def group_method
["category-1"]
end
end
TagGroup = Struct.new(:id, :name, :tags)
class User
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_accessor :id, :name, :company, :company_id, :time_zone, :active, :age,
:description, :created_at, :updated_at, :credit_limit, :password, :url,
:delivery_time, :born_at, :special_company_id, :country, :tags, :tag_ids,
:avatar, :home_picture, :email, :status, :residence_country, :phone_number,
:post_count, :lock_version, :amount, :attempts, :action, :credit_card, :gender,
:extra_special_company_id, :pictures, :picture_ids, :special_pictures,
:special_picture_ids, :uuid, :friends, :friend_ids, :special_tags, :special_tag_ids,
:citext, :hstore, :json, :jsonb, :hourly, :favorite_color
def self.build(extra_attributes = {})
attributes = {
id: 1,
name: 'New in SimpleForm!',
description: 'Hello!',
created_at: Time.now
}.merge! extra_attributes
new attributes
end
def initialize(options = {})
@new_record = false
options.each do |key, value|
send("#{key}=", value)
end if options
end
def new_record!
@new_record = true
end
def persisted?
!@new_record
end
def company_attributes=(*)
end
def tags_attributes=(*)
end
def column_for_attribute(attribute)
column_type, limit = case attribute.to_sym
when :name, :status, :password then [:string, 100]
when :description then [:text, 200]
when :age then :integer
when :credit_limit then [:decimal, 15]
when :active then :boolean
when :born_at then :date
when :delivery_time then :time
when :created_at then :datetime
when :updated_at then :timestamp
when :lock_version then :integer
when :home_picture then :string
when :amount then :integer
when :attempts then :integer
when :action then :string
when :credit_card then :string
else attribute.to_sym
end
Column.new(attribute, column_type, limit)
end
begin
require 'active_model/type'
begin
ActiveModel::Type.lookup(:text)
rescue ArgumentError # :text is no longer an ActiveModel::Type
# But we don't want our tests to depend on ActiveRecord
class ::ActiveModel::Type::Text < ActiveModel::Type::String
def type; :text; end
end
ActiveModel::Type.register(:text, ActiveModel::Type::Text)
end
def type_for_attribute(attribute)
column_type, limit = case attribute
when 'name', 'status', 'password' then [:string, 100]
when 'description' then [:text, 200]
when 'age' then :integer
when 'credit_limit' then [:decimal, 15]
when 'active' then :boolean
when 'born_at' then :date
when 'delivery_time' then :time
when 'created_at' then :datetime
when 'updated_at' then :datetime
when 'lock_version' then :integer
when 'home_picture' then :string
when 'amount' then :integer
when 'attempts' then :integer
when 'action' then :string
when 'credit_card' then :string
when 'uuid' then :string
when 'citext' then :string
when 'hstore' then [:text, 200]
when 'json' then [:text, 200]
when 'jsonb' then [:text, 200]
end
ActiveModel::Type.lookup(column_type, limit: limit)
end
rescue LoadError
end
def has_attribute?(attribute)
case attribute.to_sym
when :name, :status, :password, :description, :age,
:credit_limit, :active, :born_at, :delivery_time,
:created_at, :updated_at, :lock_version, :home_picture,
:amount, :attempts, :action, :credit_card, :uuid,
:citext, :hstore, :json, :jsonb then true
else false
end
end
def self.human_attribute_name(attribute, options = {})
case attribute
when 'name', :name
'Super User Name!'
when 'description'
'User Description!'
when 'status'
"[#{options[:base].id}] User Status!"
when 'company'
'Company Human Name!'
else
attribute.to_s.humanize
end
end
def self.reflect_on_association(association)
case association
when :company
Association.new(Company, association, :belongs_to, nil, {})
when :tags
Association.new(Tag, association, :has_many, nil, {})
when :special_tags
Association.new(Tag, association, :has_many, ->(user) { where(id: user.id) }, {})
when :first_company
Association.new(Company, association, :has_one, nil, {})
when :special_company
Association.new(Company, association, :belongs_to, nil, conditions: { id: 1 })
when :extra_special_company
Association.new(Company, association, :belongs_to, nil, conditions: proc { { id: self.id } })
when :pictures
Association.new(Picture, association, :has_many, nil, {})
when :special_pictures
Association.new(Picture, association, :has_many, proc { where(name: self.name) }, {})
when :friends
Association.new(Friend, association, :has_many, nil, {})
end
end
def errors
@errors ||= begin
errors = ActiveModel::Errors.new(self)
errors.add(:name, "cannot be blank")
errors.add(:description, 'must be longer than 15 characters')
errors.add(:age, 'is not a number')
errors.add(:age, 'must be greater than 18')
errors.add(:company, 'company must be present')
errors.add(:company_id, 'must be valid')
errors
end
end
def self.readonly_attributes
["credit_card"]
end
end
class ValidatingUser < User
include ActiveModel::Validations
validates :name, presence: true
validates :company, presence: true
validates :age, presence: true, if: proc { |user| user.name }
validates :amount, presence: true, unless: proc { |user| user.age }
validates :action, presence: true, on: :create
validates :credit_limit, presence: true, on: :save
validates :phone_number, presence: true, on: :update
validates_numericality_of :age,
greater_than_or_equal_to: 18,
less_than_or_equal_to: 99,
only_integer: true
validates_numericality_of :amount,
greater_than: :min_amount,
less_than: :max_amount,
only_integer: true
validates_numericality_of :attempts,
greater_than_or_equal_to: :min_attempts,
less_than_or_equal_to: :max_attempts,
only_integer: true
validates_length_of :name, maximum: 25, minimum: 5
validates_length_of :description, in: 15..50
validates_length_of :home_picture, is: 12
def min_amount
10
end
def max_amount
100
end
def min_attempts
1
end
def max_attempts
100
end
end
class OtherValidatingUser < User
include ActiveModel::Validations
validates_numericality_of :age,
greater_than: 17,
less_than: 100,
only_integer: true
validates_numericality_of :amount,
greater_than: proc { |user| user.age },
less_than: proc { |user| user.age + 100 },
only_integer: true
validates_numericality_of :attempts,
greater_than_or_equal_to: proc { |user| user.age },
less_than_or_equal_to: proc { |user| user.age + 100 },
only_integer: true
validates_format_of :country, with: /\w+/
validates_format_of :name, with: proc { /\w+/ }
validates_format_of :description, without: /\d+/
end
class HashBackedAuthor < Hash
extend ActiveModel::Naming
include ActiveModel::Conversion
def persisted?; false; end
def name
'hash backed author'
end
end
class UserNumber1And2 < User
end
class UserWithAttachment < User
def avatar_attachment
OpenStruct.new
end
def avatars_attachments
OpenStruct.new
end
def remote_cover_url
"/uploads/cover.png"
end
def profile_image_attacher
OpenStruct.new
end
def portrait_file_name
"portrait.png"
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/support/discovery_inputs.rb | test/support/discovery_inputs.rb | # frozen_string_literal: true
class StringInput < SimpleForm::Inputs::StringInput
def input(wrapper_options = nil)
"<section>#{super}</section>".html_safe
end
end
class NumericInput < SimpleForm::Inputs::NumericInput
def input(wrapper_options = nil)
"<section>#{super}</section>".html_safe
end
end
class CustomizedInput < SimpleForm::Inputs::StringInput
def input(wrapper_options = nil)
"<section>#{super}</section>".html_safe
end
def input_method
:text_field
end
end
class DeprecatedInput < SimpleForm::Inputs::StringInput
def input
"<section>#{super}</section>".html_safe
end
def input_method
:text_field
end
end
class CollectionSelectInput < SimpleForm::Inputs::CollectionSelectInput
def input_html_classes
super.push('chosen')
end
end
class FileInput < SimpleForm::Inputs::FileInput
def input_html_classes
super.delete_if { |html_class| html_class == :file }
super.push('file-upload')
end
end
module CustomInputs
class CustomizedInput < SimpleForm::Inputs::StringInput
def input_html_classes
super.push('customized-namespace-custom-input')
end
end
class PasswordInput < SimpleForm::Inputs::PasswordInput
def input_html_classes
super.push('password-custom-input')
end
end
class NumericInput < SimpleForm::Inputs::PasswordInput
def input_html_classes
super.push('numeric-custom-input')
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/wrapper_test.rb | test/form_builder/wrapper_test.rb | # frozen_string_literal: true
require 'test_helper'
class WrapperTest < ActionView::TestCase
test 'wrapper does not have error class for attribute without errors' do
with_form_for @user, :active
assert_no_select 'div.field_with_errors'
end
test 'wrapper does not have error class when object is not present' do
with_form_for :project, :name
assert_no_select 'div.field_with_errors'
end
test 'wrapper adds the attribute name class' do
with_form_for @user, :name
assert_select 'div.user_name'
end
test 'wrapper adds the attribute name class for nested forms' do
@user.company = Company.new(1, 'Empresa')
with_concat_form_for @user do |f|
concat(f.simple_fields_for(:company) do |company_form|
concat(company_form.input :name)
end)
end
assert_select 'div.user_company_name'
end
test 'wrapper adds the association name class' do
with_form_for @user, :company
assert_select 'div.user_company'
end
test 'wrapper adds error class for attribute with errors' do
with_form_for @user, :name
assert_select 'div.field_with_errors'
end
test 'wrapper adds error class to input for attribute with errors' do
with_form_for @user, :name, wrapper: custom_wrapper_with_input_error_class
assert_select 'div.field_with_errors'
assert_select 'input.is-invalid'
end
test 'wrapper does not add error class to input when the attribute is valid' do
with_form_for @user, :phone_number, wrapper: custom_wrapper_with_input_error_class
assert_no_select 'div.field_with_errors'
assert_no_select 'input.is-invalid'
end
test 'wrapper adds valid class for present attribute without errors' do
@user.instance_eval { undef errors }
with_form_for @user, :name, wrapper: custom_wrapper_with_input_valid_class
assert_select 'div.field_without_errors'
assert_select 'input.is-valid'
assert_no_select 'div.field_with_errors'
assert_no_select 'input.is-invalid'
end
test 'wrapper does not determine if valid class is needed when it is set to nil' do
@user.instance_eval { undef errors }
with_form_for @user, :name, wrapper: custom_wrapper_with_input_valid_class(valid_class: nil)
assert_no_select 'div.field_without_errors'
end
test 'wrapper adds hint class for attribute with a hint' do
with_form_for @user, :name, hint: 'hint'
assert_select 'div.field_with_hint'
end
test 'wrapper does not have disabled class by default' do
with_form_for @user, :active
assert_no_select 'div.disabled'
end
test 'wrapper has disabled class when input is disabled' do
with_form_for @user, :active, disabled: true
assert_select 'div.disabled'
end
test 'wrapper supports no wrapping when wrapper is false' do
with_form_for @user, :name, wrapper: false
assert_select 'form > label[for=user_name]'
assert_select 'form > input#user_name.string'
end
test 'wrapper supports no wrapping when wrapper tag is false' do
with_form_for @user, :name, wrapper: custom_wrapper_without_top_level
assert_select 'form > label[for=user_name]'
assert_select 'form > input#user_name.string'
end
test 'wrapper wraps tag adds required/optional css classes' do
with_form_for @user, :name
assert_select 'form div.input.required.string'
with_form_for @user, :age, required: false
assert_select 'form div.input.optional.integer'
end
test 'wrapper allows custom options to be given' do
with_form_for @user, :name, wrapper_html: { id: "super_cool", class: 'yay' }
assert_select 'form #super_cool.required.string.yay'
end
test 'wrapper allows tag to be given on demand' do
with_form_for @user, :name, wrapper_tag: :b
assert_select 'form b.required.string'
end
test 'wrapper allows wrapper class to be given on demand' do
with_form_for @user, :name, wrapper_class: :wrapper
assert_select 'form div.wrapper.required.string'
end
test 'wrapper skips additional classes when configured' do
swap SimpleForm, generate_additional_classes_for: %i[input label] do
with_form_for @user, :name, wrapper_class: :wrapper
assert_select 'form div.wrapper'
assert_no_select 'div.required'
assert_no_select 'div.string'
assert_no_select 'div.user_name'
end
end
test 'wrapper does not generate empty css class' do
swap SimpleForm, generate_additional_classes_for: %i[input label] do
swap_wrapper :default, custom_wrapper_without_class do
with_form_for @user, :name
assert_no_select 'div#custom_wrapper_without_class[class]'
end
end
end
# Custom wrapper test
test 'custom wrappers works' do
swap_wrapper do
with_form_for @user, :name, hint: "cool"
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
assert_no_select "section.custom_wrapper div.another_wrapper span.omg_error"
assert_select "section.custom_wrapper div.error_wrapper span.omg_error"
assert_select "section.custom_wrapper > div.omg_hint", "cool"
end
end
test 'custom wrappers can be turned off' do
swap_wrapper do
with_form_for @user, :name, another: false
assert_no_select "section.custom_wrapper div.another_wrapper label"
assert_no_select "section.custom_wrapper div.another_wrapper input.string"
assert_select "section.custom_wrapper div.error_wrapper span.omg_error"
end
end
test 'custom wrappers can have additional attributes' do
swap_wrapper :default, custom_wrapper_with_additional_attributes do
with_form_for @user, :name
assert_select "div.custom_wrapper[title='some title'][data-wrapper='test']"
end
end
test 'custom wrappers can have full error message on attributes' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :name
assert_select 'span.error', "Super User Name! cannot be blank"
end
end
test 'custom wrappers on a form basis' do
swap_wrapper :another do
with_concat_form_for(@user) do |f|
f.input :name
end
assert_no_select "section.custom_wrapper div.another_wrapper label"
assert_no_select "section.custom_wrapper div.another_wrapper input.string"
with_concat_form_for(@user, wrapper: :another) do |f|
f.input :name
end
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
end
test 'custom wrappers on input basis' do
swap_wrapper :another do
with_form_for @user, :name
assert_no_select "section.custom_wrapper div.another_wrapper label"
assert_no_select "section.custom_wrapper div.another_wrapper input.string"
output_buffer.to_s.replace ""
with_form_for @user, :name, wrapper: :another
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
output_buffer.to_s.replace ""
end
with_form_for @user, :name, wrapper: custom_wrapper
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
test 'access wrappers with indifferent access' do
swap_wrapper :another do
with_form_for @user, :name, wrapper: "another"
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
end
test 'does not duplicate label classes for different inputs' do
swap_wrapper :default, custom_wrapper_with_label_html_option do
with_concat_form_for(@user) do |f|
concat f.input :name, required: false
concat f.input :email, as: :email, required: true
end
assert_select "label.string.optional.extra-label-class[for='user_name']"
assert_select "label.email.required.extra-label-class[for='user_email']"
assert_no_select "label.string.optional.extra-label-class[for='user_email']"
end
end
test 'raise error when wrapper not found' do
assert_raise SimpleForm::WrapperNotFound do
with_form_for @user, :name, wrapper: :not_found
end
end
test 'uses wrapper for specified in config mapping' do
swap_wrapper :another do
swap SimpleForm, wrapper_mappings: { string: :another } do
with_form_for @user, :name
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
end
end
test 'uses custom wrapper mapping per form basis' do
swap_wrapper :another do
with_concat_form_for @user, wrapper_mappings: { string: :another } do |f|
concat f.input :name
end
end
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
test 'simple_fields_form reuses custom wrapper mapping per form basis' do
@user.company = Company.new(1, 'Empresa')
swap_wrapper :another do
with_concat_form_for @user, wrapper_mappings: { string: :another } do |f|
concat(f.simple_fields_for(:company) do |company_form|
concat(company_form.input(:name))
end)
end
end
assert_select "section.custom_wrapper div.another_wrapper label"
assert_select "section.custom_wrapper div.another_wrapper input.string"
end
test "input attributes class will merge with wrapper_options' classes" do
swap_wrapper :default, custom_wrapper_with_input_class do
with_concat_form_for @user do |f|
concat f.input :name, input_html: { class: 'another-class' }
end
end
assert_select "div.custom_wrapper input.string.inline-class.another-class"
end
test "input with data attributes will merge with wrapper_options' data" do
swap_wrapper :default, custom_wrapper_with_input_data_modal do
with_concat_form_for @user do |f|
concat f.input :name, input_html: { data: { modal: 'another-data', target: 'merge-data' } }
end
end
assert_select "input[data-wrapper='data-wrapper'][data-modal='another-data'][data-target='merge-data']"
end
test "input with aria attributes will merge with wrapper_options' aria" do
swap_wrapper :default, custom_wrapper_with_input_aria_modal do
with_concat_form_for @user do |f|
concat f.input :name, input_html: { aria: { modal: 'another-aria', target: 'merge-aria' } }
end
end
assert_select "input[aria-wrapper='aria-wrapper'][aria-modal='another-aria'][aria-target='merge-aria']"
end
test 'input accepts attributes in the DSL' do
swap_wrapper :default, custom_wrapper_with_input_class do
with_concat_form_for @user do |f|
concat f.input :name
end
end
assert_select "div.custom_wrapper input.string.inline-class"
end
test 'label accepts attributes in the DSL' do
swap_wrapper :default, custom_wrapper_with_label_class do
with_concat_form_for @user do |f|
concat f.input :name
end
end
assert_select "div.custom_wrapper label.string.inline-class"
end
test 'label_input accepts attributes in the DSL' do
swap_wrapper :default, custom_wrapper_with_label_input_class do
with_concat_form_for @user do |f|
concat f.input :name
end
end
assert_select "div.custom_wrapper label.string.inline-class"
assert_select "div.custom_wrapper input.string.inline-class"
end
test 'input accepts data attributes in the DSL' do
swap_wrapper :default, custom_wrapper_with_input_attributes do
with_concat_form_for @user do |f|
concat f.input :name
end
end
assert_select "div.custom_wrapper input.string[data-modal=true]"
end
test 'inline wrapper displays when there is content' do
swap_wrapper :default, custom_wrapper_with_wrapped_optional_component do
with_form_for @user, :name, hint: "cannot be blank"
assert_select 'section.custom_wrapper div.no_output_wrapper p.omg_hint', "cannot be blank"
assert_select 'p.omg_hint'
end
end
test 'inline wrapper does not display when there is no content' do
swap_wrapper :default, custom_wrapper_with_wrapped_optional_component do
with_form_for @user, :name
assert_select 'section.custom_wrapper div.no_output_wrapper'
assert_no_select 'p.omg_hint'
end
end
test 'optional wrapper does not display when there is content' do
swap_wrapper :default, custom_wrapper_with_unless_blank do
with_form_for @user, :name, hint: "can't be blank"
assert_select 'section.custom_wrapper div.no_output_wrapper'
assert_select 'div.no_output_wrapper'
assert_select 'p.omg_hint'
end
end
test 'optional wrapper does not display when there is no content' do
swap_wrapper :default, custom_wrapper_with_unless_blank do
with_form_for @user, :name
assert_no_select 'section.custom_wrapper div.no_output_wrapper'
assert_no_select 'div.no_output_wrapper'
assert_no_select 'p.omg_hint'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/error_test.rb | test/form_builder/error_test.rb | # frozen_string_literal: true
require 'test_helper'
# Tests for f.error and f.full_error
class ErrorTest < ActionView::TestCase
def with_error_for(object, *args)
with_concat_form_for(object) do |f|
f.error(*args)
end
end
def with_full_error_for(object, *args)
with_concat_form_for(object) do |f|
f.full_error(*args)
end
end
test 'error does not generate content for attribute without errors' do
with_error_for @user, :active
assert_no_select 'span.error'
end
test 'error does not generate messages when object is not present' do
with_error_for :project, :name
assert_no_select 'span.error'
end
test "error does not generate messages when object doesn't respond to errors method" do
@user.instance_eval { undef errors }
with_error_for @user, :name
assert_no_select 'span.error'
end
test 'error generates messages for attribute with single error' do
with_error_for @user, :name
assert_select 'span.error', "cannot be blank"
end
test 'error generates messages with decorated object responsive to #to_model' do
with_error_for @decorated_user, :name
assert_select 'span.error', "cannot be blank"
end
test 'error generates messages for attribute with one error when using first' do
swap SimpleForm, error_method: :first do
with_error_for @user, :age
assert_select 'span.error', 'is not a number'
end
end
test 'error generates messages for attribute with several errors when using to_sentence' do
swap SimpleForm, error_method: :to_sentence do
with_error_for @user, :age
assert_select 'span.error', 'is not a number and must be greater than 18'
end
end
test 'error is able to pass html options' do
with_error_for @user, :name, id: 'error', class: 'yay'
assert_select 'span#error.error.yay'
end
test 'error does not modify the options hash' do
options = { id: 'error', class: 'yay' }
with_error_for @user, :name, options
assert_select 'span#error.error.yay'
assert_equal({ id: 'error', class: 'yay' }, options)
end
test 'error finds errors on attribute and association' do
with_error_for @user, :company_id, as: :select,
error_method: :to_sentence, reflection: Association.new(Company, :company, {})
assert_select 'span.error', 'must be valid and company must be present'
end
test 'error generates an error tag with a clean HTML' do
with_error_for @user, :name
assert_no_select 'span.error[error_html]'
end
test 'error generates an error tag with a clean HTML when errors options are present' do
with_error_for @user, :name, error_tag: :p, error_prefix: 'Name', error_method: :first
assert_no_select 'p.error[error_html]'
assert_no_select 'p.error[error_tag]'
assert_no_select 'p.error[error_prefix]'
assert_no_select 'p.error[error_method]'
end
test 'error escapes error prefix text' do
with_error_for @user, :name, error_prefix: '<b>Name</b>'
assert_no_select 'span.error b'
end
test 'error escapes error text' do
@user.errors.add(:action, 'must not contain <b>markup</b>')
with_error_for @user, :action
assert_select 'span.error'
assert_no_select 'span.error b', 'markup'
end
test 'error generates an error message with raw HTML tags' do
with_error_for @user, :name, error_prefix: '<b>Name</b>'.html_safe
assert_select 'span.error', "Name cannot be blank"
assert_select 'span.error b', "Name"
end
test 'error adds aria-invalid attribute to inputs' do
with_form_for @user, :name, error: true
assert_select "input#user_name[name='user[name]'][aria-invalid='true']"
with_form_for @user, :name, as: :text, error: true
assert_select "textarea#user_name[name='user[name]'][aria-invalid='true']"
@user.errors.add(:active, 'must select one')
with_form_for @user, :active, as: :radio_buttons
assert_select "input#user_active_true[type=radio][name='user[active]'][aria-invalid='true']"
assert_select "input#user_active_false[type=radio][name='user[active]'][aria-invalid='true']"
with_form_for @user, :active, as: :check_boxes
assert_select "input#user_active_true[type=checkbox][aria-invalid='true']"
assert_select "input#user_active_false[type=checkbox][aria-invalid='true']"
with_form_for @user, :company_id, as: :select, error: true
assert_select "select#user_company_id[aria-invalid='true']"
@user.errors.add(:password, 'must not be blank')
with_form_for @user, :password
assert_select "input#user_password[type=password][aria-invalid='true']"
end
# FULL ERRORS
test 'full error generates a full error tag for the attribute' do
with_full_error_for @user, :name
assert_select 'span.error', "Super User Name! cannot be blank"
end
test 'full error generates a full error tag with a clean HTML' do
with_full_error_for @user, :name
assert_no_select 'span.error[error_html]'
end
test 'full error allows passing options to full error tag' do
with_full_error_for @user, :name, id: 'name_error', error_prefix: "Your name"
assert_select 'span.error#name_error', "Your name cannot be blank"
end
test 'full error does not modify the options hash' do
options = { id: 'name_error' }
with_full_error_for @user, :name, options
assert_select 'span.error#name_error', "Super User Name! cannot be blank"
assert_equal({ id: 'name_error' }, options)
end
test 'full error escapes error text' do
@user.errors.add(:action, 'must not contain <b>markup</b>')
with_full_error_for @user, :action
assert_select 'span.error'
assert_no_select 'span.error b', 'markup'
end
test 'full error uses human_attribute_name and passed object as an option to it' do
@user.errors.add(:status, 'error')
with_full_error_for @user, :status
assert_select 'span.error', "\[#{@user.id}\] User Status! error"
end
# CUSTOM WRAPPERS
test 'error with custom wrappers works' do
swap_wrapper do
with_error_for @user, :name
assert_select 'span.omg_error', "cannot be blank"
end
end
# FULL_ERROR_WRAPPER
test 'full error finds errors on association' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :company_id, as: :select
assert_select 'span.error', 'Company must be valid'
end
end
test 'full error finds errors on association with reflection' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :company_id, as: :select,
reflection: Association.new(Company, :company, {})
assert_select 'span.error', 'Company must be valid'
end
end
test 'full error can be disabled' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :company_id, as: :select, full_error: false
assert_no_select 'span.error'
end
end
test 'full error can be disabled setting error to false' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :company_id, as: :select, error: false
assert_no_select 'span.error'
end
end
# CUSTOM ERRORS
test 'input with custom error works' do
error_text = "Super User Name! cannot be blank"
with_form_for @user, :name, error: error_text
assert_select 'span.error', error_text
end
test 'input with error option as true does not use custom error' do
with_form_for @user, :name, error: true
assert_select 'span.error', "cannot be blank"
end
test 'input with custom error does not generate the error if there is no error on the attribute' do
with_form_for @user, :active, error: "Super User Active! cannot be blank"
assert_no_select 'span.error'
end
test 'input with custom error works when form does not use a model' do
with_form_for :user, :active, error: "Super User Active! cannot be blank"
assert_select 'span.error'
end
test 'input with custom error works when using full_error component' do
swap_wrapper :default, custom_wrapper_with_full_error do
error_text = "Super User Name! cannot be blank"
with_form_for @user, :name, error: error_text
assert_select 'span.error', error_text
end
end
test 'input with custom error escapes the error text' do
with_form_for @user, :name, error: 'error must not contain <b>markup</b>'
assert_select 'span.error'
assert_no_select 'span.error b', 'markup'
end
test 'input with custom error does not escape the error text if it is safe' do
with_form_for @user, :name, error: 'error must contain <b>markup</b>'.html_safe
assert_select 'span.error'
assert_select 'span.error b', 'markup'
end
test 'input with custom error escapes the error text using full_error component' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :name, error: 'error must not contain <b>markup</b>'
assert_select 'span.error'
assert_no_select 'span.error b', 'markup'
end
end
test 'input with custom error does not escape the error text if it is safe using full_error component' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :name, error: 'error must contain <b>markup</b>'.html_safe
assert_select 'span.error'
assert_select 'span.error b', 'markup'
end
end
test 'input with custom error when using full_error component does not generate the error if there is no error on the attribute' do
swap_wrapper :default, custom_wrapper_with_full_error do
with_form_for @user, :active, error: "Super User Active! can't be blank"
assert_no_select 'span.error'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/association_test.rb | test/form_builder/association_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class AssociationTest < ActionView::TestCase
def with_association_for(object, *args)
with_concat_form_for(object) do |f|
f.association(*args)
end
end
test 'builder does not allow creating an association input when no object exists' do
assert_raise ArgumentError do
with_association_for :post, :author
end
end
test 'builder association works with decorated object responsive to #to_model' do
assert_nothing_raised do
with_association_for @decorated_user, :company
end
end
test 'builder association with a block calls simple_fields_for' do
simple_form_for @user do |f|
f.association :posts do |posts_form|
assert posts_form.instance_of?(SimpleForm::FormBuilder)
end
end
end
test 'builder association forwards collection to simple_fields_for' do
calls = 0
simple_form_for @user do |f|
f.association :company, collection: Company.all do |c|
calls += 1
end
end
assert_equal 3, calls
end
test 'builder association marks input as required based on both association and attribute' do
swap SimpleForm, required_by_default: false do
with_association_for @validating_user, :company, collection: []
assert_select 'label.required'
end
end
test 'builder preloads collection association' do
value = @user.tags = Minitest::Mock.new
value.expect(:to_a, value)
with_association_for @user, :tags
assert_select 'form select.select#user_tag_ids'
assert_select 'form select option[value="1"]', 'Tag 1'
assert_select 'form select option[value="2"]', 'Tag 2'
assert_select 'form select option[value="3"]', 'Tag 3'
value.verify
end
test 'builder does not preload collection association if preload is false' do
value = @user.tags = Minitest::Mock.new
value.expect(:to_a, nil)
with_association_for @user, :tags, preload: false
assert_select 'form select.select#user_tag_ids'
assert_select 'form select option[value="1"]', 'Tag 1'
assert_select 'form select option[value="2"]', 'Tag 2'
assert_select 'form select option[value="3"]', 'Tag 3'
assert_raises MockExpectationError do
value.verify
end
end
test 'builder does not preload non-collection association' do
value = @user.company = Minitest::Mock.new
value.expect(:to_a, nil)
with_association_for @user, :company
assert_select 'form select.select#user_company_id'
assert_select 'form select option[value="1"]', 'Company 1'
assert_select 'form select option[value="2"]', 'Company 2'
assert_select 'form select option[value="3"]', 'Company 3'
assert_raises MockExpectationError do
value.verify
end
end
# ASSOCIATIONS - BELONGS TO
test 'builder creates a select for belongs_to associations' do
with_association_for @user, :company
assert_select 'form select.select#user_company_id'
assert_select 'form select option[value="1"]', 'Company 1'
assert_select 'form select option[value="2"]', 'Company 2'
assert_select 'form select option[value="3"]', 'Company 3'
end
test 'builder creates blank select if collection is nil' do
with_association_for @user, :company, collection: nil
assert_select 'form select.select#user_company_id'
assert_no_select 'form select option[value="1"]', 'Company 1'
end
test 'builder allows collection radio for belongs_to associations' do
with_association_for @user, :company, as: :radio_buttons
assert_select 'form input.radio_buttons#user_company_id_1'
assert_select 'form input.radio_buttons#user_company_id_2'
assert_select 'form input.radio_buttons#user_company_id_3'
end
test 'builder allows collection to have a proc as a condition' do
with_association_for @user, :extra_special_company
assert_select 'form select.select#user_extra_special_company_id'
assert_select 'form select option[value="1"]'
assert_no_select 'form select option[value="2"]'
assert_no_select 'form select option[value="3"]'
end
test 'builder allows collection to have a scope' do
with_association_for @user, :special_pictures
assert_select 'form select.select#user_special_picture_ids'
assert_select 'form select option[value="3"]', '3'
assert_no_select 'form select option[value="1"]'
assert_no_select 'form select option[value="2"]'
end
test 'builder allows collection to have a scope with parameter' do
with_association_for @user, :special_tags
assert_select 'form select.select#user_special_tag_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value="1"]', 'Tag 1'
assert_no_select 'form select option[value="2"]'
assert_no_select 'form select option[value="3"]'
end
test 'builder marks the record which already belongs to the user' do
@user.company_id = 2
with_association_for @user, :company, as: :radio_buttons
assert_no_select 'form input.radio_buttons#user_company_id_1[checked=checked]'
assert_select 'form input.radio_buttons#user_company_id_2[checked=checked]'
assert_no_select 'form input.radio_buttons#user_company_id_3[checked=checked]'
end
# ASSOCIATIONS - FINDERS
test 'builder uses reflection conditions to find collection' do
with_association_for @user, :special_company
assert_select 'form select.select#user_special_company_id'
assert_select 'form select option[value="1"]'
assert_no_select 'form select option[value="2"]'
assert_no_select 'form select option[value="3"]'
end
test 'builder allows overriding collection to association input' do
with_association_for @user, :company, include_blank: false,
collection: [Company.new(999, 'Teste')]
assert_select 'form select.select#user_company_id'
assert_no_select 'form select option[value="1"]'
assert_select 'form select option[value="999"]', 'Teste'
assert_select 'form select option', count: 1
end
# ASSOCIATIONS - has_*
test 'builder does not allow has_one associations' do
assert_raise ArgumentError do
with_association_for @user, :first_company, as: :radio_buttons
end
end
test 'builder does not call where if the given association does not respond to it' do
with_association_for @user, :friends
assert_select 'form select.select#user_friend_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value="1"]', 'Friend 1'
assert_select 'form select option[value="2"]', 'Friend 2'
assert_select 'form select option[value="3"]', 'Friend 3'
end
test 'builder does not call order if the given association does not respond to it' do
with_association_for @user, :pictures
assert_select 'form select.select#user_picture_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value="1"]', 'Picture 1'
assert_select 'form select option[value="2"]', 'Picture 2'
assert_select 'form select option[value="3"]', 'Picture 3'
end
test 'builder creates a select with multiple options for collection associations' do
with_association_for @user, :tags
assert_select 'form select.select#user_tag_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value="1"]', 'Tag 1'
assert_select 'form select option[value="2"]', 'Tag 2'
assert_select 'form select option[value="3"]', 'Tag 3'
end
test 'builder allows size to be overwritten for collection associations' do
with_association_for @user, :tags, input_html: { size: 10 }
assert_select 'form select[multiple=multiple][size="10"]'
end
test 'builder marks all selected records which already belongs to user' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags
assert_select 'form select option[value="1"][selected=selected]'
assert_select 'form select option[value="2"][selected=selected]'
assert_no_select 'form select option[value="3"][selected=selected]'
end
test 'builder allows a collection of check boxes for collection associations' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags, as: :check_boxes
assert_select 'form input#user_tag_ids_1[type=checkbox]'
assert_select 'form input#user_tag_ids_2[type=checkbox]'
assert_select 'form input#user_tag_ids_3[type=checkbox]'
end
test 'builder marks all selected records for collection boxes' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags, as: :check_boxes
assert_select 'form input[type=checkbox][value="1"][checked=checked]'
assert_select 'form input[type=checkbox][value="2"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="3"][checked=checked]'
end
test 'builder with collection support giving collection and item wrapper tags' do
with_association_for @user, :tags, as: :check_boxes,
collection_wrapper_tag: :ul, item_wrapper_tag: :li
assert_select 'form ul', count: 1
assert_select 'form ul li', count: 3
end
test 'builder with collection support does not change the options hash' do
options = { as: :check_boxes, collection_wrapper_tag: :ul, item_wrapper_tag: :li }
with_association_for @user, :tags, options
assert_select 'form ul', count: 1
assert_select 'form ul li', count: 3
assert_equal({ as: :check_boxes, collection_wrapper_tag: :ul, item_wrapper_tag: :li },
options)
end
test 'builder with group select considers multiple select by default' do
with_association_for @user, :tags, as: :grouped_select, group_method: :group_method
assert_select 'select[multiple="multiple"].grouped_select'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/general_test.rb | test/form_builder/general_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class FormBuilderTest < ActionView::TestCase
def with_custom_form_for(object, *args, &block)
with_concat_custom_form_for(object) do |f|
f.input(*args, &block)
end
end
test 'nested simple fields yields an instance of FormBuilder' do
simple_form_for :user do |f|
f.simple_fields_for :posts do |posts_form|
assert posts_form.instance_of?(SimpleForm::FormBuilder)
end
end
end
test 'builder input is html safe' do
simple_form_for @user do |f|
assert f.input(:name).html_safe?
end
end
test 'builder works without controller' do
stub_any_instance ActionView::TestCase, :controller, nil do
simple_form_for @user do |f|
assert f.input(:name)
end
end
end
test 'builder works with decorated object responsive to #to_model' do
assert_nothing_raised do
with_form_for @decorated_user, :name
end
end
test 'builder input allows a block to configure input' do
with_form_for @user, :name do
text_field_tag :foo, :bar, id: :cool
end
assert_no_select 'input.string'
assert_select 'input#cool'
end
test 'builder allows adding custom input mappings for default input types' do
swap SimpleForm, input_mappings: { /count$/ => :integer } do
with_form_for @user, :post_count
assert_no_select 'form input#user_post_count.string'
assert_select 'form input#user_post_count.numeric.integer'
end
end
test 'builder does not override custom input mappings for custom collection' do
swap SimpleForm, input_mappings: { /gender$/ => :check_boxes } do
with_concat_form_for @user do |f|
f.input :gender, collection: %i[male female]
end
assert_no_select 'select option', 'Male'
assert_select 'input[type=checkbox][value=male]'
end
end
test 'builder allows to skip input_type class' do
swap SimpleForm, generate_additional_classes_for: %i[label wrapper] do
with_form_for @user, :post_count
assert_no_select "form input#user_post_count.integer"
assert_select "form input#user_post_count"
end
end
test 'builder allows to add additional classes only for wrapper' do
swap SimpleForm, generate_additional_classes_for: [:wrapper] do
with_form_for @user, :post_count
assert_no_select "form input#user_post_count.string"
assert_no_select "form label#user_post_count.string"
assert_select "form div.input.string"
end
end
test 'builder allows adding custom input mappings for integer input types' do
swap SimpleForm, input_mappings: { /lock_version/ => :hidden } do
with_form_for @user, :lock_version
assert_no_select 'form input#user_lock_version.integer'
assert_select 'form input#user_lock_version.hidden'
end
end
test 'builder uses the first matching custom input map when more than one matches' do
swap SimpleForm, input_mappings: { /count$/ => :integer, /^post_/ => :password } do
with_form_for @user, :post_count
assert_no_select 'form input#user_post_count.password'
assert_select 'form input#user_post_count.numeric.integer'
end
end
test 'builder uses the custom map only for matched attributes' do
swap SimpleForm, input_mappings: { /lock_version/ => :hidden } do
with_form_for @user, :post_count
assert_no_select 'form input#user_post_count.hidden'
assert_select 'form input#user_post_count.string'
end
end
test 'builder allow to use numbers in the model name' do
user = UserNumber1And2.build(tags: [Tag.new(nil, 'Tag1')])
with_concat_form_for(user, url: '/') do |f|
f.simple_fields_for(:tags) do |tags|
tags.input :name
end
end
assert_select 'form .user_number1_and2_tags_name'
assert_no_select 'form .user_number1_and2_tags_1_name'
end
# INPUT TYPES
test 'builder generates text fields for string columns' do
with_form_for @user, :name
assert_select 'form input#user_name.string'
end
test 'builder generates text areas for text columns' do
with_form_for @user, :description
assert_no_select 'form input#user_description.string'
assert_select 'form textarea#user_description.text'
end
test 'builder generates text areas for text columns when hinted' do
with_form_for @user, :description, as: :text
assert_no_select 'form input#user_description.string'
assert_select 'form textarea#user_description.text'
end
test 'builder generates text field for text columns when hinted' do
with_form_for @user, :description, as: :string
assert_no_select 'form textarea#user_description.text'
assert_select 'form input#user_description.string'
end
test 'builder generates text areas for hstore columns' do
with_form_for @user, :hstore
assert_no_select 'form input#user_hstore.string'
assert_select 'form textarea#user_hstore.text'
end
test 'builder generates text areas for json columns' do
with_form_for @user, :json
assert_no_select 'form input#user_json.string'
assert_select 'form textarea#user_json.text'
end
test 'builder generates text areas for jsonb columns' do
with_form_for @user, :jsonb
assert_no_select 'form input#user_jsonb.string'
assert_select 'form textarea#user_jsonb.text'
end
test 'builder generates a checkbox for boolean columns' do
with_form_for @user, :active
assert_select 'form input[type=checkbox]#user_active.boolean'
end
test 'builder uses integer text field for integer columns' do
with_form_for @user, :age
assert_select 'form input#user_age.numeric.integer'
end
test 'builder generates decimal text field for decimal columns' do
with_form_for @user, :credit_limit
assert_select 'form input#user_credit_limit.numeric.decimal'
end
test 'builder generates uuid fields for uuid columns' do
with_form_for @user, :uuid
if defined? ActiveModel::Type
assert_select 'form input#user_uuid.string.string'
else
assert_select 'form input#user_uuid.string.uuid'
end
end
test 'builder generates string fields for citext columns' do
with_form_for @user, :citext
assert_select 'form input#user_citext.string'
end
test 'builder generates password fields for columns that matches password' do
with_form_for @user, :password
assert_select 'form input#user_password.password'
end
test 'builder generates country fields for columns that matches country' do
with_form_for @user, :residence_country
assert_select 'form select#user_residence_country.country'
end
test 'builder generates time_zone fields for columns that matches time_zone' do
with_form_for @user, :time_zone
assert_select 'form select#user_time_zone.time_zone'
end
test 'builder generates email fields for columns that matches email' do
with_form_for @user, :email
assert_select 'form input#user_email.string.email'
end
test 'builder generates tel fields for columns that matches phone' do
with_form_for @user, :phone_number
assert_select 'form input#user_phone_number.string.tel'
end
test 'builder generates url fields for columns that matches url' do
with_form_for @user, :url
assert_select 'form input#user_url.string.url'
end
test 'builder generates date select for date columns' do
with_form_for @user, :born_at
assert_select 'form select#user_born_at_1i.date'
end
test 'builder generates time select for time columns' do
with_form_for @user, :delivery_time
assert_select 'form select#user_delivery_time_4i.time'
end
test 'builder generates datetime select for datetime columns' do
with_form_for @user, :created_at
assert_select 'form select#user_created_at_1i.datetime'
end
test 'builder generates datetime select for timestamp columns' do
with_form_for @user, :updated_at
assert_select 'form select#user_updated_at_1i.datetime'
end
test 'builder generates file input for ActiveStorage >= 5.2 and Refile >= 0.2.0 <= 0.4.0' do
with_form_for UserWithAttachment.build, :avatar
assert_select 'form input#user_with_attachment_avatar.file'
end
test 'builder generates file input for ActiveStorage::Attached::Many' do
with_form_for UserWithAttachment.build, :avatars
assert_select 'form input#user_with_attachment_avatars.file'
end
test 'builder generates file input for Refile >= 0.3.0 and CarrierWave >= 0.2.2' do
with_form_for UserWithAttachment.build, :cover
assert_select 'form input#user_with_attachment_cover.file'
end
test 'builder generates file input for Refile >= 0.4.0 and Shrine >= 0.9.0' do
with_form_for UserWithAttachment.build, :profile_image
assert_select 'form input#user_with_attachment_profile_image.file'
end
test 'builder generates file input for Paperclip ~> 2.0' do
with_form_for UserWithAttachment.build, :portrait
assert_select 'form input#user_with_attachment_portrait.file'
end
test 'build generates select if a collection is given' do
with_form_for @user, :age, collection: 1..60
assert_select 'form select#user_age.select'
end
test 'builder does not generate url fields for columns that contain only the letters url' do
with_form_for @user, :hourly
assert_no_select 'form input#user_url.string.url'
assert_select 'form input#user_hourly.string'
end
test 'builder allows overriding default input type for text' do
with_form_for @user, :name, as: :text
assert_no_select 'form input#user_name'
assert_select 'form textarea#user_name.text'
end
test 'builder allows overriding default input type for radio_buttons' do
with_form_for @user, :active, as: :radio_buttons
assert_no_select 'form input[type=checkbox]'
assert_select 'form input.radio_buttons[type=radio]', count: 2
end
test 'builder allows overriding default input type for string' do
with_form_for @user, :born_at, as: :string
assert_no_select 'form select'
assert_select 'form input#user_born_at.string'
end
# COMMON OPTIONS
# Remove this test when SimpleForm.form_class is removed in 4.x
test 'builder adds chosen form class' do
SimpleForm.deprecator.silence do
swap SimpleForm, form_class: :my_custom_class do
with_form_for @user, :name
assert_select 'form.my_custom_class'
end
end
end
# Remove this test when SimpleForm.form_class is removed in 4.x
test 'builder adds chosen form class and default form class' do
SimpleForm.deprecator.silence do
swap SimpleForm, form_class: "my_custom_class", default_form_class: "my_default_class" do
with_form_for @user, :name
assert_select 'form.my_custom_class.my_default_class'
end
end
end
test 'builder adds default form class' do
swap SimpleForm, default_form_class: "default_class" do
with_form_for @user, :name
assert_select 'form.default_class'
end
end
test 'builder allows passing options to input' do
with_form_for @user, :name, input_html: { class: 'my_input', id: 'my_input' }
assert_select 'form input#my_input.my_input.string'
end
test 'builder does not propagate input options to wrapper' do
with_form_for @user, :name, input_html: { class: 'my_input', id: 'my_input' }
assert_no_select 'form div.input.my_input.string'
assert_select 'form input#my_input.my_input.string'
end
test 'builder does not propagate input options to wrapper with custom wrapper' do
swap_wrapper :default, custom_wrapper_with_wrapped_input do
with_form_for @user, :name, input_html: { class: 'my_input' }
assert_no_select 'form div.input.my_input'
assert_select 'form input.my_input.string'
end
end
test 'builder does not propagate label options to wrapper with custom wrapper' do
swap_wrapper :default, custom_wrapper_with_wrapped_label do
with_form_for @user, :name, label_html: { class: 'my_label' }
assert_no_select 'form div.label.my_label'
assert_select 'form label.my_label.string'
end
end
test 'builder generates an input with label' do
with_form_for @user, :name
assert_select 'form label.string[for=user_name]', /Name/
end
test 'builder is able to disable the label for an input' do
with_form_for @user, :name, label: false
assert_no_select 'form label'
end
test 'builder is able to disable the label for an input and return a html safe string' do
with_form_for @user, :name, label: false, wrapper: custom_wrapper_with_wrapped_label_input
assert_select 'form input#user_name'
end
test 'builder uses custom label' do
with_form_for @user, :name, label: 'Yay!'
assert_select 'form label', /Yay!/
end
test 'builder passes options to label' do
with_form_for @user, :name, label_html: { id: "cool" }
assert_select 'form label#cool', /Name/
end
test 'builder does not generate hints for an input' do
with_form_for @user, :name
assert_no_select 'span.hint'
end
test 'builder is able to add a hint for an input' do
with_form_for @user, :name, hint: 'test'
assert_select 'span.hint', 'test'
end
test 'builder is able to disable a hint even if it exists in i18n' do
store_translations(:en, simple_form: { hints: { name: 'Hint test' } }) do
stub_any_instance(SimpleForm::Inputs::Base, :hint, -> { raise 'Never' }) do
with_form_for @user, :name, hint: false
assert_no_select 'span.hint'
end
end
end
test 'builder passes options to hint' do
with_form_for @user, :name, hint: 'test', hint_html: { id: "cool" }
assert_select 'span.hint#cool', 'test'
end
test 'builder generates errors for attribute without errors' do
with_form_for @user, :credit_limit
assert_no_select 'span.errors'
end
test 'builder generates errors for attribute with errors' do
with_form_for @user, :name
assert_select 'span.error', "cannot be blank"
end
test 'builder is able to disable showing errors for an input' do
with_form_for @user, :name, error: false
assert_no_select 'span.error'
end
test 'builder passes options to errors' do
with_form_for @user, :name, error_html: { id: "cool" }
assert_select 'span.error#cool', "cannot be blank"
end
test 'placeholder does not be generated when set to false' do
store_translations(:en, simple_form: { placeholders: { user: {
name: 'Name goes here'
} } }) do
with_form_for @user, :name, placeholder: false
assert_no_select 'input[placeholder]'
end
end
# DEFAULT OPTIONS
%i[input input_field].each do |method|
test "builder receives a default argument and pass it to the inputs when calling '#{method}'" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f|
f.public_send(method, :name)
end
assert_select 'input.default_class'
end
test "builder receives a default argument and pass it to the inputs without changing the defaults when calling '#{method}'" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f|
concat(f.public_send(method, :name))
concat(f.public_send(method, :credit_limit))
end
assert_select "input.string.default_class[name='user[name]']"
assert_no_select "input.string[name='user[credit_limit]']"
end
test "builder receives a default argument and pass it to the inputs and nested form when calling '#{method}'" do
@user.company = Company.new(1, 'Empresa')
with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f|
concat(f.public_send(method, :name))
concat(f.simple_fields_for(:company) do |company_form|
concat(company_form.public_send(method, :name))
end)
end
assert_select "input.string.default_class[name='user[name]']"
assert_select "input.string.default_class[name='user[company_attributes][name]']"
end
end
test "builder receives a default argument and pass it to the inputs when calling 'input', respecting the specific options" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f|
f.input :name, input_html: { id: 'specific_id' }
end
assert_select 'input.default_class#specific_id'
end
test "builder receives a default argument and pass it to the inputs when calling 'input_field', respecting the specific options" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f|
f.input_field :name, id: 'specific_id'
end
assert_select 'input.default_class#specific_id'
end
test "builder receives a default argument and pass it to the inputs when calling 'input', overwriting the defaults with specific options" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f|
f.input :name, input_html: { id: 'specific_id' }
end
assert_select 'input.default_class#specific_id'
end
test "builder receives a default argument and pass it to the inputs when calling 'input_field', overwriting the defaults with specific options" do
with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f|
f.input_field :name, id: 'specific_id'
end
assert_select 'input.default_class#specific_id'
end
# WITHOUT OBJECT
test 'builder generates properly when object is not present' do
with_form_for :project, :name
assert_select 'form input.string#project_name'
end
test 'builder generates password fields based on attribute name when object is not present' do
with_form_for :project, :password_confirmation
assert_select 'form input[type=password].password#project_password_confirmation'
end
test 'builder generates text fields by default for all attributes when object is not present' do
with_form_for :project, :created_at
assert_select 'form input.string#project_created_at'
with_form_for :project, :budget
assert_select 'form input.string#project_budget'
end
test 'builder allows overriding input type when object is not present' do
with_form_for :project, :created_at, as: :datetime
assert_select 'form select.datetime#project_created_at_1i'
with_form_for :project, :budget, as: :decimal
assert_select 'form input.decimal#project_budget'
end
# CUSTOM FORM BUILDER
test 'custom builder inherits mappings' do
with_custom_form_for @user, :email
assert_select 'form input[type=email]#user_email.custom'
end
test 'form with CustomMapTypeFormBuilder uses custom map type builder' do
with_concat_custom_mapping_form_for(:user) do |user|
assert user.instance_of?(CustomMapTypeFormBuilder)
end
end
test 'form with CustomMapTypeFormBuilder uses custom mapping' do
with_concat_custom_mapping_form_for(:user) do |user|
assert_equal SimpleForm::Inputs::StringInput, user.class.mappings[:custom_type]
end
end
test 'form without CustomMapTypeFormBuilder does not use custom mapping' do
with_concat_form_for(:user) do |user|
assert_nil user.class.mappings[:custom_type]
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/label_test.rb | test/form_builder/label_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class LabelTest < ActionView::TestCase
def with_label_for(object, *args, &block)
with_concat_form_for(object) do |f|
f.label(*args, &block)
end
end
test 'builder generates a label for the attribute' do
with_label_for @user, :name
assert_select 'label.string[for=user_name]', /Name/
end
test 'builder generates a label for the attribute with decorated object responsive to #to_model' do
with_label_for @decorated_user, :name
assert_select 'label.string[for=user_name]', /Name/
end
test 'builder generates a label for the boolean attribute' do
with_label_for @user, :name, as: :boolean
assert_select 'label.boolean[for=user_name]', /Name/
assert_no_select 'label[as=boolean]'
end
test 'builder generates a label component tag with a clean HTML' do
with_label_for @user, :name
assert_no_select 'label.string[label_html]'
end
test 'builder adds a required class to label if the attribute is required' do
with_label_for @validating_user, :name
assert_select 'label.string.required[for=validating_user_name]', /Name/
end
test 'builder adds a disabled class to label if the attribute is disabled' do
with_label_for @validating_user, :name, disabled: true
assert_select 'label.string.disabled[for=validating_user_name]', /Name/
end
test 'builder does not add a disabled class to label if the attribute is not disabled' do
with_label_for @validating_user, :name, disabled: false
assert_no_select 'label.string.disabled[for=validating_user_name]', /Name/
end
test 'builder escapes label text' do
with_label_for @user, :name, label: '<script>alert(1337)</script>', required: false
assert_no_select 'label.string script'
end
test 'builder does not escape label text if it is safe' do
with_label_for @user, :name, label: '<script>alert(1337)</script>'.html_safe, required: false
assert_select 'label.string script', "alert(1337)"
end
test 'builder allows passing options to label tag' do
with_label_for @user, :name, label: 'My label', id: 'name_label'
assert_select 'label.string#name_label', /My label/
end
test 'builder label generates label tag with clean HTML' do
with_label_for @user, :name, label: 'My label', required: true, id: 'name_label'
assert_select 'label.string#name_label', /My label/
assert_no_select 'label[label]'
assert_no_select 'label[required]'
end
test 'builder does not modify the options hash' do
options = { label: 'My label', id: 'name_label' }
with_label_for @user, :name, options
assert_select 'label.string#name_label', /My label/
assert_equal({ label: 'My label', id: 'name_label' }, options)
end
test 'builder fallbacks to default label when string is given' do
with_label_for @user, :name, 'Nome do usuário'
assert_select 'label', 'Nome do usuário'
assert_no_select 'label.string'
end
test 'builder fallbacks to default label when block is given' do
with_label_for @user, :name do
'Nome do usuário'
end
assert_select 'label', 'Nome do usuário'
assert_no_select 'label.string'
end
test 'builder allows label order to be changed' do
swap SimpleForm, label_text: proc { |l, r| "#{l}:" } do
with_label_for @user, :age
assert_select 'label.integer[for=user_age]', "Age:"
end
end
test 'configuration allow set label text for wrappers' do
swap_wrapper :default, custom_wrapper_with_label_text do
with_concat_form_for(@user) do |f|
concat f.input :age
end
assert_select "label.integer[for=user_age]", "**Age**"
end
end
test 'configuration allow set rewritten label tag for wrappers' do
swap_wrapper :default, custom_wrapper_with_custom_label_component do
with_concat_form_for(@user) do |f|
concat f.input :age
end
assert_select "span.integer.user_age", /Age/
end
end
test 'builder allows custom formatting when label is explicitly specified' do
swap SimpleForm, label_text: ->(l, r, explicit_label) { explicit_label ? l : "#{l.titleize}:" } do
with_label_for @user, :time_zone, 'What is your home time zone?'
assert_select 'label[for=user_time_zone]', 'What is your home time zone?'
end
end
test 'builder allows custom formatting when label is generated' do
swap SimpleForm, label_text: ->(l, r, explicit_label) { explicit_label ? l : "#{l.titleize}:" } do
with_label_for @user, :time_zone
assert_select 'label[for=user_time_zone]', 'Time Zone:'
end
end
test 'builder allows label specific `label_text` option' do
with_label_for @user, :time_zone, label_text: ->(l, _, _) { "#{l.titleize}:" }
assert_no_select 'label[label_text]'
assert_select 'label[for=user_time_zone]', 'Time Zone:'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/button_test.rb | test/form_builder/button_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class ButtonTest < ActionView::TestCase
def with_button_for(object, *args)
with_concat_form_for(object) do |f|
f.button(*args)
end
end
test 'builder creates buttons' do
with_button_for :post, :submit
assert_select 'form input.button[type=submit][value="Save Post"]'
end
test 'builder creates buttons with options' do
with_button_for :post, :submit, class: 'my_button'
assert_select 'form input.button.my_button[type=submit][value="Save Post"]'
end
test 'builder does not modify the options hash' do
options = { class: 'my_button' }
with_button_for :post, :submit, options
assert_select 'form input.button.my_button[type=submit][value="Save Post"]'
assert_equal({ class: 'my_button' }, options)
end
test 'builder creates buttons for records' do
@user.new_record!
with_button_for @user, :submit
assert_select 'form input.button[type=submit][value="Create User"]'
end
test "builder uses the default class from the configuration" do
swap SimpleForm, button_class: 'btn' do
with_button_for :post, :submit
assert_select 'form input.btn[type=submit][value="Save Post"]'
end
end
if ActionView::Helpers::FormBuilder.method_defined?(:button)
test "allows to use Rails button helper when available" do
with_button_for :post, :button, 'Save!'
assert_select 'form button.button[type=submit]', 'Save!'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/error_notification_test.rb | test/form_builder/error_notification_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
# Tests for f.error_notification
class ErrorNotificationTest < ActionView::TestCase
def with_error_notification_for(object, options = {}, &block)
with_concat_form_for(object) do |f|
f.error_notification(options)
end
end
test 'error notification is not generated when the object has no error' do
assert @validating_user.valid?
with_error_notification_for @validating_user
assert_no_select 'p.error_notification'
end
test 'error notification is not generated for forms without objects' do
with_error_notification_for :user
assert_no_select 'p.error_notification'
end
test 'error notification is generated when the object has some error' do
with_error_notification_for @user
assert_select 'p.error_notification', 'Please review the problems below:'
end
test 'error notification uses I18n based on model to generate the notification message' do
store_translations(:en, simple_form: { error_notification: { user:
'Alguns erros foram encontrados para o usuário:'
} }) do
with_error_notification_for @user
assert_select 'p.error_notification', 'Alguns erros foram encontrados para o usuário:'
end
end
test 'error notification uses I18n fallbacking to default message' do
store_translations(:en, simple_form: { error_notification: {
default_message: 'Opa! Alguns erros foram encontrados, poderia verificar?'
} }) do
with_error_notification_for @user
assert_select 'p.error_notification', 'Opa! Alguns erros foram encontrados, poderia verificar?'
end
end
test 'error notification allows passing the notification message' do
with_error_notification_for @user, message: 'Erro encontrado ao criar usuario'
assert_select 'p.error_notification', 'Erro encontrado ao criar usuario'
end
test 'error notification accepts other html options' do
with_error_notification_for @user, id: 'user_error_message', class: 'form_error'
assert_select 'p#user_error_message.form_error.error_notification'
end
test 'error notification allows configuring the wrapper element' do
swap SimpleForm, error_notification_tag: :div do
with_error_notification_for @user
assert_select 'div.error_notification'
end
end
test 'error notification can contain HTML tags' do
with_error_notification_for @user, message: 'Erro encontrado ao criar <b>usuário</b>'
assert_select 'p.error_notification', 'Erro encontrado ao criar usuário'
assert_select 'p.error_notification b', 'usuário'
end
test 'error notification uses I18n based on model to generate the notification message and accepts HTML' do
store_translations(:en, simple_form: { error_notification: { user:
'Alguns erros foram encontrados para o <b>usuário</b>:'
} }) do
with_error_notification_for @user
assert_select 'p.error_notification', 'Alguns erros foram encontrados para o usuário:'
assert_select 'p.error_notification b', 'usuário'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/hint_test.rb | test/form_builder/hint_test.rb | # frozen_string_literal: true
require 'test_helper'
# Tests for f.hint
class HintTest < ActionView::TestCase
def with_hint_for(object, *args)
with_concat_form_for(object) do |f|
f.hint(*args)
end
end
test 'hint does not be generated by default' do
with_hint_for @user, :name
assert_no_select 'span.hint'
end
test 'hint is generated with optional text' do
with_hint_for @user, :name, hint: 'Use with care...'
assert_select 'span.hint', 'Use with care...'
end
test 'hint is generated with decorated object responsive to #to_model' do
with_hint_for @decorated_user, :name, hint: 'Use with care...'
assert_select 'span.hint', 'Use with care...'
end
test 'hint does not modify the options hash' do
options = { hint: 'Use with care...' }
with_hint_for @user, :name, options
assert_select 'span.hint', 'Use with care...'
assert_equal({ hint: 'Use with care...' }, options)
end
test 'hint is generated cleanly with optional text' do
with_hint_for @user, :name, hint: 'Use with care...', hint_tag: :span
assert_no_select 'span.hint[hint]'
assert_no_select 'span.hint[hint_tag]'
assert_no_select 'span.hint[hint_html]'
end
test 'hint uses the current component tag set' do
with_hint_for @user, :name, hint: 'Use with care...', hint_tag: :p
assert_select 'p.hint', 'Use with care...'
end
test 'hint is able to pass html options' do
with_hint_for @user, :name, hint: 'Yay!', id: 'hint', class: 'yay'
assert_select 'span#hint.hint.yay'
end
test 'hint is output as html_safe' do
with_hint_for @user, :name, hint: '<b>Bold</b> and not...'.html_safe
assert_select 'span.hint', 'Bold and not...'
assert_select 'span.hint b', 'Bold'
end
test 'builder escapes hint text' do
with_hint_for @user, :name, hint: '<script>alert(1337)</script>'
assert_no_select 'span.hint script'
end
# Without attribute name
test 'hint without attribute name' do
with_hint_for @validating_user, 'Hello World!'
assert_select 'span.hint', 'Hello World!'
end
test 'hint without attribute name generates component tag with a clean HTML' do
with_hint_for @validating_user, 'Hello World!'
assert_no_select 'span.hint[hint]'
assert_no_select 'span.hint[hint_html]'
end
test 'hint without attribute name uses the current component tag set' do
with_hint_for @user, 'Hello World!', hint_tag: :p
assert_no_select 'p.hint[hint]'
assert_no_select 'p.hint[hint_html]'
assert_no_select 'p.hint[hint_tag]'
end
test 'hint without attribute name is able to pass html options' do
with_hint_for @user, 'Yay', id: 'hint', class: 'yay'
assert_select 'span#hint.hint.yay', 'Yay'
end
# I18n
test 'hint uses i18n based on model, action, and attribute to lookup translation' do
store_translations(:en, simple_form: { hints: { user: {
edit: { name: 'Content of this input will be truncated...' }
} } }) do
with_hint_for @user, :name
assert_select 'span.hint', 'Content of this input will be truncated...'
end
end
test 'hint uses i18n with model and attribute to lookup translation' do
store_translations(:en, simple_form: { hints: { user: {
name: 'Content of this input will be capitalized...'
} } }) do
with_hint_for @user, :name
assert_select 'span.hint', 'Content of this input will be capitalized...'
end
end
test 'hint uses i18n under defaults namespace to lookup translation' do
store_translations(:en, simple_form: {
hints: { defaults: { name: 'Content of this input will be downcased...' } }
}) do
with_hint_for @user, :name
assert_select 'span.hint', 'Content of this input will be downcased...'
end
end
test 'hint uses i18n with lookup for association name' do
store_translations(:en, simple_form: { hints: {
user: { company: 'My company!' }
} } ) do
with_hint_for @user, :company_id, as: :string, reflection: Association.new(Company, :company, {})
assert_select 'span.hint', /My company!/
end
end
test 'hint outputs translations as html_safe' do
store_translations(:en, simple_form: { hints: { user: {
edit: { name: '<b>This is bold</b> and this is not...' }
} } }) do
with_hint_for @user, :name
assert_select 'span.hint', 'This is bold and this is not...'
end
end
# No object
test 'hint generates properly when object is not present' do
with_hint_for :project, :name, hint: 'Test without object'
assert_select 'span.hint', 'Test without object'
end
# Custom wrappers
test 'hint with custom wrappers works' do
swap_wrapper do
with_hint_for @user, :name, hint: "cannot be blank"
assert_select 'div.omg_hint', "cannot be blank"
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/form_builder/input_field_test.rb | test/form_builder/input_field_test.rb | # frozen_string_literal: true
require 'test_helper'
# Tests for f.input_field
class InputFieldTest < ActionView::TestCase
test "builder input_field only renders the input tag, nothing else" do
with_input_field_for @user, :name
assert_select 'form > input.required.string'
assert_no_select 'div.string'
assert_no_select 'label'
assert_no_select '.hint'
end
test 'builder input_field allows overriding default input type' do
with_input_field_for @user, :name, as: :text
assert_no_select 'input#user_name'
assert_select 'textarea#user_name.text'
end
test 'builder input_field generates input type based on column type' do
with_input_field_for @user, :age
assert_select 'input[type=number].integer#user_age'
end
test 'builder input_field is able to disable any component' do
with_input_field_for @user, :age, html5: false
assert_no_select 'input[html5=false]#user_age'
assert_select 'input[type=text].integer#user_age'
end
test 'builder input_field allows passing options to input tag' do
with_input_field_for @user, :name, id: 'name_input', class: 'name'
assert_select 'input.string.name#name_input'
end
test 'builder input_field does not modify the options hash' do
options = { id: 'name_input', class: 'name' }
with_input_field_for @user, :name, options
assert_select 'input.string.name#name_input'
assert_equal({ id: 'name_input', class: 'name' }, options)
end
test 'builder input_field generates an input tag with a clean HTML' do
with_input_field_for @user, :name, as: :integer, class: 'name'
assert_no_select 'input.integer[input_html]'
assert_no_select 'input.integer[as]'
end
test 'builder input_field uses i18n to translate placeholder text' do
store_translations(:en, simple_form: { placeholders: { user: {
name: 'Name goes here'
} } }) do
with_input_field_for @user, :name
assert_select 'input.string[placeholder="Name goes here"]'
end
end
test 'builder input_field uses min_max component' do
with_input_field_for @other_validating_user, :age, as: :integer
assert_select 'input[min="18"]'
end
test 'builder input_field does not use pattern component by default' do
with_input_field_for @other_validating_user, :country, as: :string
assert_no_select 'input[pattern="\w+"]'
end
test 'builder input_field infers pattern from attributes' do
with_input_field_for @other_validating_user, :country, as: :string, pattern: true
assert_select "input:match('pattern', ?)", /\w+/
end
test 'builder input_field accepts custom pattern' do
with_input_field_for @other_validating_user, :country, as: :string, pattern: '\d+'
assert_select "input:match('pattern', ?)", /\\d+/
end
test 'builder input_field uses readonly component' do
with_input_field_for @other_validating_user, :age, as: :integer, readonly: true
assert_select 'input.integer.readonly[readonly]'
end
test 'builder input_field uses maxlength component' do
with_input_field_for @validating_user, :name, as: :string
assert_select 'input.string[maxlength="25"]'
end
test 'builder input_field uses minlength component' do
with_input_field_for @validating_user, :name, as: :string
assert_select 'input.string[minlength="5"]'
end
test 'builder collection input_field generates input tag with a clean HTML' do
with_input_field_for @user, :status, collection: %w[Open Closed],
class: 'status', label_method: :to_s, value_method: :to_s
assert_no_select 'select.status[input_html]'
assert_no_select 'select.status[collection]'
assert_no_select 'select.status[label_method]'
assert_no_select 'select.status[value_method]'
end
test 'build input_field does not treat "boolean_style" as a HTML attribute' do
with_input_field_for @user, :active, boolean_style: :nested
assert_no_select 'input.boolean[boolean_style]'
end
test 'build input_field does not treat "prompt" as a HTML attribute' do
with_input_field_for @user, :attempts, collection: [1,2,3,4,5], prompt: :translate
assert_no_select 'select[prompt]'
end
test 'build input_field without pattern component use the pattern string' do
swap_wrapper :default, custom_wrapper_with_html5_components do
with_input_field_for @user, :name, pattern: '\w+'
assert_select "input:match('pattern', ?)", /\w+/
end
end
test 'build input_field without placeholder component use the placeholder string' do
swap_wrapper :default, custom_wrapper_with_html5_components do
with_input_field_for @user, :name, placeholder: 'Placeholder'
assert_select 'input[placeholder="Placeholder"]'
end
end
test 'build input_field without maxlength component use the maxlength string' do
swap_wrapper :default, custom_wrapper_with_html5_components do
with_input_field_for @user, :name, maxlength: 5
assert_select 'input[maxlength="5"]'
end
end
test 'build input_field without minlength component use the minlength string' do
swap_wrapper :default, custom_wrapper_with_html5_components do
with_input_field_for @user, :name, minlength: 5
assert_select 'input[minlength="5"]'
end
end
test 'build input_field without readonly component use the readonly string' do
swap_wrapper :default, custom_wrapper_with_html5_components do
with_input_field_for @user, :name, readonly: true
assert_select 'input[readonly="readonly"]'
end
end
test 'adds valid class to input_field when it is configured' do
swap SimpleForm, input_field_valid_class: 'is-valid' do
@user.instance_eval { undef errors }
with_input_field_for @user, :name
assert_select 'input.string.required.is-valid'
end
end
test 'adds error class to input_field when it is configured' do
swap SimpleForm, input_field_error_class: 'is-invalid' do
with_input_field_for @user, :name
assert_select 'input.string.required.is-invalid'
end
end
test 'does not add validation classes to input_field when it is not configured' do
swap SimpleForm, input_field_error_class: nil, input_field_valid_class: nil do
with_input_field_for @user, :name
assert_select 'input.string.required'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/action_view_extensions/form_helper_test.rb | test/action_view_extensions/form_helper_test.rb | # frozen_string_literal: true
require 'test_helper'
class FormHelperTest < ActionView::TestCase
test 'SimpleForm for yields an instance of FormBuilder' do
simple_form_for :user do |f|
assert f.instance_of?(SimpleForm::FormBuilder)
end
end
test 'SimpleForm adds default class to form' do
with_concat_form_for(:user)
assert_select 'form.simple_form'
end
test 'SimpleForm allows overriding default form class' do
swap SimpleForm, default_form_class: "my_custom_class" do
with_concat_form_for :user, html: { class: "override_class" }
assert_no_select 'form.my_custom_class'
assert_select 'form.override_class'
end
end
# Remove this test when SimpleForm.form_class is removed in 4.x
test 'SimpleForm allows overriding default form class, but not form class' do
SimpleForm.deprecator.silence do
swap SimpleForm, form_class: "fixed_class", default_form_class: "my_custom_class" do
with_concat_form_for :user, html: { class: "override_class" }
assert_no_select 'form.my_custom_class'
assert_select 'form.fixed_class.override_class'
end
end
end
test 'SimpleForm uses default browser validations by default' do
with_concat_form_for(:user)
assert_no_select 'form[novalidate]'
end
test 'SimpleForm does not use default browser validations if specified in the configuration options' do
swap SimpleForm, browser_validations: false do
with_concat_form_for(:user)
assert_select 'form[novalidate="novalidate"]'
end
end
test 'disabled browser validations overrides default configuration' do
with_concat_form_for(:user, html: { novalidate: true })
assert_select 'form[novalidate="novalidate"]'
end
test 'enabled browser validations overrides disabled configuration' do
swap SimpleForm, browser_validations: false do
with_concat_form_for(:user, html: { novalidate: false })
assert_no_select 'form[novalidate]'
end
end
test 'SimpleForm adds object name as css class to form when object is not present' do
with_concat_form_for(:user, html: { novalidate: true })
assert_select 'form.simple_form.user'
end
test 'SimpleForm adds :as option as css class to form when object is not present' do
with_concat_form_for(:user, as: 'superuser')
assert_select 'form.simple_form.superuser'
end
test 'SimpleForm adds object class name with new prefix as css class to form if record is not persisted' do
@user.new_record!
with_concat_form_for(@user)
assert_select 'form.simple_form.new_user'
end
test 'SimpleForm adds :as option with new prefix as css class to form if record is not persisted' do
@user.new_record!
with_concat_form_for(@user, as: 'superuser')
assert_select 'form.simple_form.new_superuser'
end
test 'SimpleForm adds edit class prefix as css class to form if record is persisted' do
with_concat_form_for(@user)
assert_select 'form.simple_form.edit_user'
end
test 'SimpleForm adds :as options with edit prefix as css class to form if record is persisted' do
with_concat_form_for(@user, as: 'superuser')
assert_select 'form.simple_form.edit_superuser'
end
test 'SimpleForm adds last object name as css class to form when there is array of objects' do
with_concat_form_for([Company.new, @user])
assert_select 'form.simple_form.edit_user'
end
test 'SimpleForm does not add object class to form if css_class is specified' do
with_concat_form_for(:user, html: { class: nil })
assert_no_select 'form.user'
end
test 'SimpleForm adds custom class to form if css_class is specified' do
with_concat_form_for(:user, html: { class: 'my_class' })
assert_select 'form.my_class'
end
test 'passes options to SimpleForm' do
with_concat_form_for(:user, url: '/account', html: { id: 'my_form' })
assert_select 'form#my_form'
assert_select 'form[action="/account"]'
end
test 'form_for yields an instance of FormBuilder' do
with_concat_form_for(:user) do |f|
assert f.instance_of?(SimpleForm::FormBuilder)
end
end
test 'fields_for with a hash like model yields an instance of FormBuilder' do
with_concat_fields_for(:author, HashBackedAuthor.new) do |f|
assert f.instance_of?(SimpleForm::FormBuilder)
f.input :name
end
assert_select "input[name='author[name]'][value='hash backed author']"
end
test 'custom error proc is not destructive' do
swap_field_error_proc do
result = nil
simple_form_for :user do |f|
result = simple_fields_for 'address' do
'hello'
end
end
assert_equal 'hello', result
end
end
test 'custom error proc survives an exception' do
swap_field_error_proc do
begin
simple_form_for :user do |f|
simple_fields_for 'address' do
raise 'an exception'
end
end
rescue StandardError
end
end
end
test 'SimpleForm for swaps default action view field_error_proc' do
expected_error_proc = -> {}
swap SimpleForm, field_error_proc: expected_error_proc do
simple_form_for :user do |f|
assert_equal expected_error_proc, ::ActionView::Base.field_error_proc
end
end
end
private
def swap_field_error_proc(expected_error_proc = -> {})
swap ActionView::Base, field_error_proc: expected_error_proc do
yield
assert_equal expected_error_proc, ActionView::Base.field_error_proc
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/action_view_extensions/builder_test.rb | test/action_view_extensions/builder_test.rb | # frozen_string_literal: true
require 'test_helper'
class BuilderTest < ActionView::TestCase
def with_custom_form_for(object, *args, &block)
with_concat_custom_form_for(object) do |f|
assert f.instance_of?(CustomFormBuilder)
yield f
end
end
def with_collection_radio_buttons(object, attribute, collection, value_method, text_method, options = {}, html_options = {}, &block)
with_concat_form_for(object) do |f|
f.collection_radio_buttons attribute, collection, value_method, text_method, options, html_options, &block
end
end
def with_collection_check_boxes(object, attribute, collection, value_method, text_method, options = {}, html_options = {}, &block)
with_concat_form_for(object) do |f|
f.collection_check_boxes attribute, collection, value_method, text_method, options, html_options, &block
end
end
# COLLECTION RADIO
test "collection radio accepts a collection and generate inputs from value method" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=radio][value=true]#user_active_true'
assert_select 'form input[type=radio][value=false]#user_active_false'
end
test "collection radio accepts a collection and generate inputs from label method" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s
assert_select 'form label.collection_radio_buttons[for=user_active_true]', 'true'
assert_select 'form label.collection_radio_buttons[for=user_active_false]', 'false'
end
test "collection radio handles camelized collection values for labels correctly" do
with_collection_radio_buttons @user, :active, %w[Yes No], :to_s, :to_s
assert_select 'form label.collection_radio_buttons[for=user_active_yes]', 'Yes'
assert_select 'form label.collection_radio_buttons[for=user_active_no]', 'No'
end
test "collection radio sanitizes collection values for labels correctly" do
with_collection_radio_buttons @user, :name, ['$0.99', '$1.99'], :to_s, :to_s
assert_select 'label.collection_radio_buttons[for=user_name_0_99]', '$0.99'
assert_select 'label.collection_radio_buttons[for=user_name_1_99]', '$1.99'
end
test "collection radio checks the correct value to local variables" do
user = User.build(active: false)
with_collection_radio_buttons user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=radio][value=true]'
assert_select 'form input[type=radio][value=false][checked=checked]'
end
test "collection radio accepts checked item" do
with_collection_radio_buttons @user, :active, [[1, true], [0, false]], :last, :first, checked: true
assert_select 'form input[type=radio][value=true][checked=checked]'
assert_no_select 'form input[type=radio][value=false][checked=checked]'
end
test "collection radio accepts checked item which has a value of false" do
with_collection_radio_buttons @user, :active, [[1, true], [0, false]], :last, :first, checked: false
assert_no_select 'form input[type=radio][value=true][checked=checked]'
assert_select 'form input[type=radio][value=false][checked=checked]'
end
test "collection radio accepts multiple disabled items" do
collection = [[1, true], [0, false], [2, 'other']]
with_collection_radio_buttons @user, :active, collection, :last, :first, disabled: [true, false]
assert_select 'form input[type=radio][value=true][disabled=disabled]'
assert_select 'form input[type=radio][value=false][disabled=disabled]'
assert_no_select 'form input[type=radio][value=other][disabled=disabled]'
end
test "collection radio accepts single disable item" do
collection = [[1, true], [0, false]]
with_collection_radio_buttons @user, :active, collection, :last, :first, disabled: true
assert_select 'form input[type=radio][value=true][disabled=disabled]'
assert_no_select 'form input[type=radio][value=false][disabled=disabled]'
end
test "collection radio accepts html options as input" do
collection = [[1, true], [0, false]]
with_collection_radio_buttons @user, :active, collection, :last, :first, {}, class: 'special-radio'
assert_select 'form input[type=radio][value=true].special-radio#user_active_true'
assert_select 'form input[type=radio][value=false].special-radio#user_active_false'
end
test "collection radio wraps the collection in the given collection wrapper tag" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: :ul
assert_select 'form ul input[type=radio]', count: 2
end
test "collection radio does not render any wrapper tag by default" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
end
test "collection radio does not wrap the collection when given falsy values" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: false
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
end
test "collection radio uses the given class for collection wrapper tag" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s,
collection_wrapper_tag: :ul, collection_wrapper_class: "items-list"
assert_select 'form ul.items-list input[type=radio]', count: 2
end
test "collection radio uses no class for collection wrapper tag when no wrapper tag is given" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s,
collection_wrapper_class: "items-list"
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
assert_no_select '.items-list'
end
test "collection radio uses no class for collection wrapper tag by default" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: :ul
assert_select 'form ul'
assert_no_select 'form ul[class]'
end
test "collection radio wrap items in a span tag by default" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s
assert_select 'form span input[type=radio][value=true]#user_active_true + label'
assert_select 'form span input[type=radio][value=false]#user_active_false + label'
end
test "collection radio wraps each item in the given item wrapper tag" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s, item_wrapper_tag: :li
assert_select 'form li input[type=radio]', count: 2
end
test "collection radio does not wrap each item when given explicitly falsy value" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s, item_wrapper_tag: false
assert_select 'form input[type=radio]'
assert_no_select 'form span input[type=radio]'
end
test "collection radio uses the given class for item wrapper tag" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: :li, item_wrapper_class: "inline"
assert_select "form li.inline input[type=radio]", count: 2
end
test "collection radio uses no class for item wrapper tag when no wrapper tag is given" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: nil, item_wrapper_class: "inline"
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form li'
assert_no_select '.inline'
end
test "collection radio uses no class for item wrapper tag by default" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: :li
assert_select "form li", count: 2
assert_no_select "form li[class]"
end
test "collection radio does not wrap input inside the label" do
with_collection_radio_buttons @user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=radio] + label'
assert_no_select 'form label input'
end
test "collection radio accepts a block to render the label as radio button wrapper" do
with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
b.label { b.radio_button }
end
assert_select 'label[for=user_active_true] > input#user_active_true[type=radio]'
assert_select 'label[for=user_active_false] > input#user_active_false[type=radio]'
end
test "collection radio accepts a block to change the order of label and radio button" do
with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
b.label + b.radio_button
end
assert_select 'label[for=user_active_true] + input#user_active_true[type=radio]'
assert_select 'label[for=user_active_false] + input#user_active_false[type=radio]'
end
test "collection radio with block helpers accept extra html options" do
with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
b.label(class: "radio_button") + b.radio_button(class: "radio_button")
end
assert_select 'label.radio_button[for=user_active_true] + input#user_active_true.radio_button[type=radio]'
assert_select 'label.radio_button[for=user_active_false] + input#user_active_false.radio_button[type=radio]'
end
test "collection radio with block helpers allows access to current text and value" do
with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
b.label(:"data-value" => b.value) { b.radio_button + b.text }
end
assert_select 'label[for=user_active_true][data-value=true]', 'true' do
assert_select 'input#user_active_true[type=radio]'
end
assert_select 'label[for=user_active_false][data-value=false]', 'false' do
assert_select 'input#user_active_false[type=radio]'
end
end
test "collection radio with block helpers allows access to the current object item in the collection to access extra properties" do
with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
b.label(class: b.object) { b.radio_button + b.text }
end
assert_select 'label.true[for=user_active_true]', 'true' do
assert_select 'input#user_active_true[type=radio]'
end
assert_select 'label.false[for=user_active_false]', 'false' do
assert_select 'input#user_active_false[type=radio]'
end
end
test "collection radio with block helpers does not leak the template" do
with_concat_form_for(@user) do |f|
collection_input = f.collection_radio_buttons :active, [true, false], :to_s, :to_s do |b|
b.label(class: b.object) { b.radio_button + b.text }
end
concat collection_input
concat f.hidden_field :name
end
assert_select 'label.true[for=user_active_true]', text: 'true', count: 1 do
assert_select 'input#user_active_true[type=radio]'
end
assert_select 'label.false[for=user_active_false]', text: 'false', count: 1 do
assert_select 'input#user_active_false[type=radio]'
end
end
# COLLECTION CHECK BOX
test "collection check box accepts a collection and generate a series of checkboxes for value method" do
collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')]
with_collection_check_boxes @user, :tag_ids, collection, :id, :name
assert_select 'form input#user_tag_ids_1[type=checkbox][value="1"]'
assert_select 'form input#user_tag_ids_2[type=checkbox][value="2"]'
end
test "collection check box generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection" do
collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')]
with_collection_check_boxes @user, :tag_ids, collection, :id, :name
assert_select "form input[type=hidden][name='user[tag_ids][]'][value='']", count: 1
end
test "collection check box accepts a collection and generate a series of checkboxes with labels for label method" do
collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')]
with_collection_check_boxes @user, :tag_ids, collection, :id, :name
assert_select 'form label.collection_check_boxes[for=user_tag_ids_1]', 'Tag 1'
assert_select 'form label.collection_check_boxes[for=user_tag_ids_2]', 'Tag 2'
end
test "collection check box handles camelized collection values for labels correctly" do
with_collection_check_boxes @user, :active, %w[Yes No], :to_s, :to_s
assert_select 'form label.collection_check_boxes[for=user_active_yes]', 'Yes'
assert_select 'form label.collection_check_boxes[for=user_active_no]', 'No'
end
test "collection check box sanitizes collection values for labels correctly" do
with_collection_check_boxes @user, :name, ['$0.99', '$1.99'], :to_s, :to_s
assert_select 'label.collection_check_boxes[for=user_name_0_99]', '$0.99'
assert_select 'label.collection_check_boxes[for=user_name_1_99]', '$1.99'
end
test "collection check box checks the correct value to local variables" do
user = User.build(tag_ids: [1, 3])
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes user, :tag_ids, collection, :first, :last
assert_select 'form input[type=checkbox][value="1"][checked=checked]'
assert_select 'form input[type=checkbox][value="3"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="2"][checked=checked]'
end
test "collection check box accepts selected values as :checked option" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, checked: [1, 3]
assert_select 'form input[type=checkbox][value="1"][checked=checked]'
assert_select 'form input[type=checkbox][value="3"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="2"][checked=checked]'
end
test "collection check boxes accepts selected string values as :checked option" do
collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: %w[1 3]
assert_select 'input[type=checkbox][value="1"][checked=checked]'
assert_select 'input[type=checkbox][value="3"][checked=checked]'
assert_no_select 'input[type=checkbox][value="2"][checked=checked]'
end
test "collection check box accepts a single checked value" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, checked: 3
assert_select 'form input[type=checkbox][value="3"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="1"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="2"][checked=checked]'
end
test "collection check box accepts selected values as :checked option and override the model values" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
@user.tag_ids = [2]
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, checked: [1, 3]
assert_select 'form input[type=checkbox][value="1"][checked=checked]'
assert_select 'form input[type=checkbox][value="3"][checked=checked]'
assert_no_select 'form input[type=checkbox][value="2"][checked=checked]'
end
test "collection check box accepts multiple disabled items" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, disabled: [1, 3]
assert_select 'form input[type=checkbox][value="1"][disabled=disabled]'
assert_select 'form input[type=checkbox][value="3"][disabled=disabled]'
assert_no_select 'form input[type=checkbox][value="2"][disabled=disabled]'
end
test "collection check box accepts single disable item" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, disabled: 1
assert_select 'form input[type=checkbox][value="1"][disabled=disabled]'
assert_no_select 'form input[type=checkbox][value="3"][disabled=disabled]'
assert_no_select 'form input[type=checkbox][value="2"][disabled=disabled]'
end
test "collection check box accepts a proc to disabled items" do
collection = (1..3).map { |i| [i, "Tag #{i}"] }
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, disabled: proc { |i| i.first == 1 }
assert_select 'form input[type=checkbox][value="1"][disabled=disabled]'
assert_no_select 'form input[type=checkbox][value="3"][disabled=disabled]'
assert_no_select 'form input[type=checkbox][value="2"][disabled=disabled]'
end
test "collection check box accepts html options" do
collection = [[1, 'Tag 1'], [2, 'Tag 2']]
with_collection_check_boxes @user, :tag_ids, collection, :first, :last, {}, class: 'check'
assert_select 'form input.check[type=checkbox][value="1"]'
assert_select 'form input.check[type=checkbox][value="2"]'
end
test "collection check box with fields for" do
collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')]
with_concat_form_for(@user) do |f|
f.fields_for(:post) do |p|
p.collection_check_boxes :tag_ids, collection, :id, :name
end
end
assert_select 'form input#user_post_tag_ids_1[type=checkbox][value="1"]'
assert_select 'form input#user_post_tag_ids_2[type=checkbox][value="2"]'
assert_select 'form label.collection_check_boxes[for=user_post_tag_ids_1]', 'Tag 1'
assert_select 'form label.collection_check_boxes[for=user_post_tag_ids_2]', 'Tag 2'
end
test "collection check boxes wraps the collection in the given collection wrapper tag" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: :ul
assert_select 'form ul input[type=checkbox]', count: 2
end
test "collection check boxes does not render any wrapper tag by default" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
test "collection check boxes does not wrap the collection when given falsy values" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: false
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
test "collection check boxes uses the given class for collection wrapper tag" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s,
collection_wrapper_tag: :ul, collection_wrapper_class: "items-list"
assert_select 'form ul.items-list input[type=checkbox]', count: 2
end
test "collection check boxes uses no class for collection wrapper tag when no wrapper tag is given" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s,
collection_wrapper_class: "items-list"
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
assert_no_select '.items-list'
end
test "collection check boxes uses no class for collection wrapper tag by default" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s, collection_wrapper_tag: :ul
assert_select 'form ul'
assert_no_select 'form ul[class]'
end
test "collection check boxes wrap items in a span tag by default" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s
assert_select 'form span input[type=checkbox]', count: 2
end
test "collection check boxes wraps each item in the given item wrapper tag" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s, item_wrapper_tag: :li
assert_select 'form li input[type=checkbox]', count: 2
end
test "collection check boxes does not wrap each item when given explicitly falsy value" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s, item_wrapper_tag: false
assert_select 'form input[type=checkbox]'
assert_no_select 'form span input[type=checkbox]'
end
test "collection check boxes uses the given class for item wrapper tag" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: :li, item_wrapper_class: "inline"
assert_select "form li.inline input[type=checkbox]", count: 2
end
test "collection check boxes uses no class for item wrapper tag when no wrapper tag is given" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: nil, item_wrapper_class: "inline"
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form li'
assert_no_select '.inline'
end
test "collection check boxes uses no class for item wrapper tag by default" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s,
item_wrapper_tag: :li
assert_select "form li", count: 2
assert_no_select "form li[class]"
end
test "collection check box does not wrap input inside the label" do
with_collection_check_boxes @user, :active, [true, false], :to_s, :to_s
assert_select 'form input[type=checkbox] + label'
assert_no_select 'form label input'
end
test "collection check boxes accepts a block to render the label as check box wrapper" do
with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
b.label { b.check_box }
end
assert_select 'label[for=user_active_true] > input#user_active_true[type=checkbox]'
assert_select 'label[for=user_active_false] > input#user_active_false[type=checkbox]'
end
test "collection check boxes accepts a block to change the order of label and check box" do
with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
b.label + b.check_box
end
assert_select 'label[for=user_active_true] + input#user_active_true[type=checkbox]'
assert_select 'label[for=user_active_false] + input#user_active_false[type=checkbox]'
end
test "collection check boxes with block helpers accept extra html options" do
with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
b.label(class: "check_box") + b.check_box(class: "check_box")
end
assert_select 'label.check_box[for=user_active_true] + input#user_active_true.check_box[type=checkbox]'
assert_select 'label.check_box[for=user_active_false] + input#user_active_false.check_box[type=checkbox]'
end
test "collection check boxes with block helpers allows access to current text and value" do
with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
b.label(:"data-value" => b.value) { b.check_box + b.text }
end
assert_select 'label[for=user_active_true][data-value=true]', 'true' do
assert_select 'input#user_active_true[type=checkbox]'
end
assert_select 'label[for=user_active_false][data-value=false]', 'false' do
assert_select 'input#user_active_false[type=checkbox]'
end
end
test "collection check boxes with block helpers allows access to the current object item in the collection to access extra properties" do
with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
b.label(class: b.object) { b.check_box + b.text }
end
assert_select 'label.true[for=user_active_true]', 'true' do
assert_select 'input#user_active_true[type=checkbox]'
end
assert_select 'label.false[for=user_active_false]', 'false' do
assert_select 'input#user_active_false[type=checkbox]'
end
end
test "collection check boxes with block helpers does not leak the template" do
with_concat_form_for(@user) do |f|
collection_input = f.collection_check_boxes :active, [true, false], :to_s, :to_s do |b|
b.label(class: b.object) { b.check_box + b.text }
end
concat collection_input
concat f.hidden_field :name
end
assert_select 'label.true[for=user_active_true]', text: 'true', count: 1 do
assert_select 'input#user_active_true[type=checkbox]'
end
assert_select 'label.false[for=user_active_false]', text: 'false', count: 1 do
assert_select 'input#user_active_false[type=checkbox]'
end
end
# SIMPLE FIELDS
test "simple fields for is available and yields an instance of FormBuilder" do
with_concat_form_for(@user) do |f|
f.simple_fields_for(:posts) do |posts_form|
assert posts_form.instance_of?(SimpleForm::FormBuilder)
end
end
end
test "fields for with a hash like model yields an instance of FormBuilder" do
with_concat_form_for(:user) do |f|
f.simple_fields_for(:author, HashBackedAuthor.new) do |author|
assert author.instance_of?(SimpleForm::FormBuilder)
author.input :name
end
end
assert_select "input[name='user[author][name]'][value='hash backed author']"
end
test "fields for yields an instance of CustomBuilder if main builder is a CustomBuilder" do
with_custom_form_for(:user) do |f|
f.simple_fields_for(:company) do |company|
assert company.instance_of?(CustomFormBuilder)
end
end
end
test "fields for yields an instance of FormBuilder if it was set in options" do
with_custom_form_for(:user) do |f|
f.simple_fields_for(:company, builder: SimpleForm::FormBuilder) do |company|
assert company.instance_of?(SimpleForm::FormBuilder)
end
end
end
test "fields inherits wrapper option from the parent form" do
swap_wrapper :another do
simple_form_for(:user, wrapper: :another) do |f|
f.simple_fields_for(:company) do |company|
assert_equal :another, company.options[:wrapper]
end
end
end
end
test "fields overrides wrapper option from the parent form" do
swap_wrapper :another do
simple_form_for(:user, wrapper: :another) do |f|
f.simple_fields_for(:company, wrapper: false) do |company|
assert_equal false, company.options[:wrapper]
end
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/components/label_test.rb | test/components/label_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
# Isolated tests for label without triggering f.label.
class IsolatedLabelTest < ActionView::TestCase
def with_label_for(object, attribute_name, type, options = {})
with_concat_form_for(object) do |f|
options[:reflection] = Association.new(Company, :company, {}) if options.delete(:setup_association)
SimpleForm::Inputs::Base.new(f, attribute_name, nil, type, options).label
end
end
test 'label generates a default humanized description' do
with_label_for @user, :name, :string
assert_select 'label[for=user_name]', /Name/
end
test 'label allows a customized description' do
with_label_for @user, :name, :string, label: 'My label!'
assert_select 'label[for=user_name]', /My label!/
end
test 'label uses human attribute name from object when available' do
with_label_for @user, :description, :text
assert_select 'label[for=user_description]', /User Description!/
end
test 'label uses human_attribute_name and passed object as an option to it' do
with_label_for @user, :status, :text
assert_select 'label[for=user_status]', /\[#{@user.id}\] User Status!/
end
test 'label uses human attribute name based on association name' do
with_label_for @user, :company_id, :string, setup_association: true
assert_select 'label', /Company Human Name!/
end
test 'label uses i18n based on model, action, and attribute to lookup translation' do
@controller.action_name = "new"
store_translations(:en, simple_form: { labels: { user: {
new: { description: 'Nova descrição' }
} } }) do
with_label_for @user, :description, :text
assert_select 'label[for=user_description]', /Nova descrição/
end
end
test 'label fallbacks to new when action is create' do
@controller.action_name = "create"
store_translations(:en, simple_form: { labels: { user: {
new: { description: 'Nova descrição' }
} } }) do
with_label_for @user, :description, :text
assert_select 'label[for=user_description]', /Nova descrição/
end
end
test 'label does not explode while looking for i18n translation when action is not set' do
def @controller.action_name; nil; end
assert_nothing_raised do
with_label_for @user, :description, :text
end
assert_select 'label[for=user_description]'
end
test 'label uses i18n based on model and attribute to lookup translation' do
store_translations(:en, simple_form: { labels: { user: {
description: 'Descrição'
} } }) do
with_label_for @user, :description, :text
assert_select 'label[for=user_description]', /Descrição/
end
end
test 'label uses i18n under defaults to lookup translation' do
store_translations(:en, simple_form: { labels: { defaults: { age: 'Idade' } } }) do
with_label_for @user, :age, :integer
assert_select 'label[for=user_age]', /Idade/
end
end
test 'label does not use i18n label if translate is false' do
swap SimpleForm, translate_labels: false do
store_translations(:en, simple_form: { labels: { defaults: { age: 'Idade' } } }) do
with_label_for @user, :age, :integer
assert_select 'label[for=user_age]', /Age/
end
end
end
test 'label uses i18n with lookup for association name' do
store_translations(:en, simple_form: { labels: {
user: { company: 'My company!' }
} }) do
with_label_for @user, :company_id, :string, setup_association: true
assert_select 'label[for=user_company_id]', /My company!/
end
end
test 'label uses i18n under defaults namespace to lookup for association name' do
store_translations(:en, simple_form: { labels: {
defaults: { company: 'Plataformatec' }
} }) do
with_label_for @user, :company, :string, setup_association: true
assert_select 'form label', /Plataformatec/
end
end
test 'label does correct i18n lookup for nested models with nested translation' do
@user.company = Company.new(1, 'Empresa')
store_translations(:en, simple_form: { labels: {
user: { name: 'Usuario', company: { name: 'Nome da empresa' } }
} }) do
with_concat_form_for @user do |f|
concat f.input :name
concat(f.simple_fields_for(:company) do |company_form|
concat(company_form.input :name)
end)
end
assert_select 'label[for=user_name]', /Usuario/
assert_select 'label[for=user_company_attributes_name]', /Nome da empresa/
end
end
test 'label does correct i18n lookup for nested models with no nested translation' do
@user.company = Company.new(1, 'Empresa')
store_translations(:en, simple_form: { labels: {
user: { name: 'Usuario' },
company: { name: 'Nome da empresa' }
} }) do
with_concat_form_for @user do |f|
concat f.input :name
concat(f.simple_fields_for(:company) do |company_form|
concat(company_form.input :name)
end)
end
assert_select 'label[for=user_name]', /Usuario/
assert_select 'label[for=user_company_attributes_name]', /Nome da empresa/
end
end
test 'label does correct i18n lookup for nested has_many models with no nested translation' do
@user.tags = [Tag.new(1, 'Empresa')]
store_translations(:en, simple_form: { labels: {
user: { name: 'Usuario' },
tags: { name: 'Nome da empresa' }
} }) do
with_concat_form_for @user do |f|
concat f.input :name
concat(f.simple_fields_for(:tags, child_index: "new_index") do |tags_form|
concat(tags_form.input :name)
end)
end
assert_select 'label[for=user_name]', /Usuario/
assert_select 'label[for=user_tags_attributes_new_index_name]', /Nome da empresa/
end
end
test 'label has css class from type' do
with_label_for @user, :name, :string
assert_select 'label.string'
with_label_for @user, :description, :text
assert_select 'label.text'
with_label_for @user, :age, :integer
assert_select 'label.integer'
with_label_for @user, :born_at, :date
assert_select 'label.date'
with_label_for @user, :created_at, :datetime
assert_select 'label.datetime'
end
test 'label does not have css class from type when generate_additional_classes_for does not include :label' do
swap SimpleForm, generate_additional_classes_for: %i[wrapper input] do
with_label_for @user, :name, :string
assert_no_select 'label.string'
with_label_for @user, :description, :text
assert_no_select 'label.text'
with_label_for @user, :age, :integer
assert_no_select 'label.integer'
with_label_for @user, :born_at, :date
assert_no_select 'label.date'
with_label_for @user, :created_at, :datetime
assert_no_select 'label.datetime'
end
end
test 'label does not generate empty css class' do
swap SimpleForm, generate_additional_classes_for: %i[wrapper input] do
with_label_for @user, :name, :string
assert_no_select 'label[class]'
end
end
test 'label obtains required from ActiveModel::Validations when it is included' do
with_label_for @validating_user, :name, :string
assert_select 'label.required'
with_label_for @validating_user, :status, :string
assert_select 'label.optional'
end
test 'label does not obtain required from ActiveModel::Validations when generate_additional_classes_for does not include :label' do
swap SimpleForm, generate_additional_classes_for: %i[wrapper input] do
with_label_for @validating_user, :name, :string
assert_no_select 'label.required'
with_label_for @validating_user, :status, :string
assert_no_select 'label.optional'
end
end
test 'label allows overriding required when ActiveModel::Validations is included' do
with_label_for @validating_user, :name, :string, required: false
assert_select 'label.optional'
with_label_for @validating_user, :status, :string, required: true
assert_select 'label.required'
end
test 'label is required by default when ActiveModel::Validations is not included' do
with_label_for @user, :name, :string
assert_select 'label.required'
end
test 'label is able to disable required when ActiveModel::Validations is not included' do
with_label_for @user, :name, :string, required: false
assert_no_select 'label.required'
end
test 'label adds required text when required' do
with_label_for @user, :name, :string
assert_select 'label.required abbr[title=required]', '*'
end
test 'label does not have required text in no required inputs' do
with_label_for @user, :name, :string, required: false
assert_no_select 'form label abbr'
end
test 'label uses i18n to find required text' do
store_translations(:en, simple_form: { required: { text: 'campo requerido' } }) do
with_label_for @user, :name, :string
assert_select 'form label abbr[title="campo requerido"]', '*'
end
end
test 'label uses custom i18n scope to find required text' do
store_translations(:en, my_scope: { required: { text: 'Pflichtfeld' } }) do
swap SimpleForm, i18n_scope: :my_scope do
with_label_for @user, :name, :string
assert_select 'form label abbr[title="Pflichtfeld"]', '*'
end
end
end
test 'label uses i18n to find required mark' do
store_translations(:en, simple_form: { required: { mark: '*-*' } }) do
with_label_for @user, :name, :string
assert_select 'form label abbr', '*-*'
end
end
test 'label uses custom i18n scope to find required mark' do
store_translations(:en, my_scope: { required: { mark: '!!' } }) do
swap SimpleForm, i18n_scope: :my_scope do
with_label_for @user, :name, :string
assert_select 'form label abbr', '!!'
end
end
end
test 'label uses i18n to find required string tag' do
store_translations(:en, simple_form: { required: { html: '<span class="required" title="requerido">*</span>' } }) do
with_label_for @user, :name, :string
assert_no_select 'form label abbr'
assert_select 'form label span.required[title=requerido]', '*'
end
end
test 'label uses custom i18n scope to find required string tag' do
store_translations(:en, my_scope: { required: { html: '<span class="mandatory" title="Pflichtfeld">!!</span>' } }) do
swap SimpleForm, i18n_scope: :my_scope do
with_label_for @user, :name, :string
assert_no_select 'form label abbr'
assert_select 'form label span.mandatory[title=Pflichtfeld]', '!!'
end
end
end
test 'label allows overwriting input id' do
with_label_for @user, :name, :string, input_html: { id: 'my_new_id' }
assert_select 'label[for=my_new_id]'
end
test 'label allows overwriting of for attribute' do
with_label_for @user, :name, :string, label_html: { for: 'my_new_id' }
assert_select 'label[for=my_new_id]'
end
test 'label allows overwriting of for attribute with input_html not containing id' do
with_label_for @user, :name, :string, label_html: { for: 'my_new_id' }, input_html: { class: 'foo' }
assert_select 'label[for=my_new_id]'
end
test 'label uses default input id when it was not overridden' do
with_label_for @user, :name, :string, input_html: { class: 'my_new_id' }
assert_select 'label[for=user_name]'
end
test 'label is generated properly when object is not present' do
with_label_for :project, :name, :string
assert_select 'label[for=project_name]', /Name/
end
test 'label includes for attribute for select collection' do
with_label_for @user, :sex, :select, collection: %i[male female]
assert_select 'label[for=user_sex]'
end
test 'label uses i18n properly when object is not present' do
store_translations(:en, simple_form: { labels: {
project: { name: 'Nome' }
} }) do
with_label_for :project, :name, :string
assert_select 'label[for=project_name]', /Nome/
end
end
test 'label adds required by default when object is not present' do
with_label_for :project, :name, :string
assert_select 'label.required[for=project_name]'
with_label_for :project, :description, :string, required: false
assert_no_select 'label.required[for=project_description]'
end
test 'label adds chosen label class' do
swap SimpleForm, label_class: :my_custom_class do
with_label_for @user, :name, :string
assert_select 'label.my_custom_class'
end
end
test 'label strips extra classes even when label_class is nil' do
swap SimpleForm, label_class: nil do
with_label_for @user, :name, :string
assert_select "label[class='string required']"
assert_no_select "label[class='string required ']"
assert_no_select "label[class=' string required']"
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/components/custom_components_test.rb | test/components/custom_components_test.rb | # frozen_string_literal: true
require 'test_helper'
# Module that represents a custom component.
module Numbers
def number(wrapper_options = nil)
@number ||= options[:number].to_s.html_safe
end
end
# Module that represents a custom component.
module InputGroup
def prepend(wrapper_options = nil)
span_tag = content_tag(:span, options[:prepend], class: 'input-group-text')
template.content_tag(:div, span_tag, class: 'input-group-prepend')
end
def append(wrapper_options = nil)
span_tag = content_tag(:span, options[:append], class: 'input-group-text')
template.content_tag(:div, span_tag, class: 'input-group-append')
end
end
class CustomComponentsTest < ActionView::TestCase
test 'includes the custom components' do
SimpleForm.include_component Numbers
custom_wrapper = SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :number, wrap_with: { tag: 'div', class: 'number' }
end
with_form_for @user, :name, number: 1, wrapper: custom_wrapper
assert_select 'div.number', text: '1'
end
test 'includes custom components and use it as optional in the wrapper' do
SimpleForm.include_component InputGroup
custom_wrapper = SimpleForm.build tag: :div, class: 'custom_wrapper' do |b|
b.use :label
b.optional :prepend
b.use :input
b.use :append
end
with_form_for @user, :name, prepend: true, wrapper: custom_wrapper
assert_select 'div.input-group-prepend > span.input-group-text'
assert_select 'div.input-group-append > span.input-group-text'
end
test 'raises a TypeError when the component is not a Module' do
component = 'MyComponent'
exception = assert_raises TypeError do
SimpleForm.include_component(component)
end
assert_equal exception.message, "SimpleForm.include_component expects a module but got: String"
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/generators/simple_form_generator_test.rb | test/generators/simple_form_generator_test.rb | # frozen_string_literal: true
require 'test_helper'
class SimpleFormGeneratorTest < Rails::Generators::TestCase
tests SimpleForm::Generators::InstallGenerator
destination File.expand_path('../../tmp', __FILE__)
setup :prepare_destination
teardown { rm_rf(destination_root) }
test 'generates example locale file' do
run_generator
assert_file 'config/locales/simple_form.en.yml'
end
test 'generates the simple_form initializer' do
run_generator
assert_file 'config/initializers/simple_form.rb',
/config\.default_wrapper = :default/, /config\.boolean_style = :nested/
end
test 'generates the simple_form initializer with the bootstrap wrappers' do
run_generator %w[--bootstrap]
assert_file 'config/initializers/simple_form.rb',
/config\.default_wrapper = :default/, /config\.boolean_style = :nested/
assert_file 'config/initializers/simple_form_bootstrap.rb', /config\.wrappers :vertical_form/,
/config\.wrappers :horizontal_form/, /config\.default_wrapper = :vertical_form/
end
test 'generates the simple_form initializer with the foundation wrappers' do
run_generator %w[--foundation]
assert_file 'config/initializers/simple_form.rb',
/config\.default_wrapper = :default/, /config\.boolean_style = :nested/
assert_file 'config/initializers/simple_form_foundation.rb', /config\.wrappers :vertical_form/,
/config\.default_wrapper = :vertical_form/, /config\.item_wrapper_tag = :div/
end
%w[erb haml slim].each do |engine|
test "generates the scaffold template when using #{engine}" do
run_generator ['-e', engine]
assert_file "lib/templates/#{engine}/scaffold/_form.html.#{engine}"
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/collection_radio_buttons_input_test.rb | test/inputs/collection_radio_buttons_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class CollectionRadioButtonsInputTest < ActionView::TestCase
test 'input generates boolean radio buttons by default for radio types' do
with_input_for @user, :active, :radio_buttons
assert_select 'input[type=radio][value=true].radio_buttons#user_active_true'
assert_select 'input[type=radio][value=false].radio_buttons#user_active_false'
end
test 'input as radio generates internal labels by default' do
with_input_for @user, :active, :radio_buttons
assert_select 'label[for=user_active_true]', 'Yes'
assert_select 'label[for=user_active_false]', 'No'
end
test 'input as radio generates internal labels with accurate `for` values with nested boolean style' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons
assert_select 'label[for=user_active_true]', 'Yes'
assert_select 'label[for=user_active_false]', 'No'
end
end
test 'nested label does not duplicate input id' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons, id: 'nested_id'
assert_select 'input#user_active_true'
assert_no_select 'label#user_active_true'
end
end
test 'input as radio uses i18n to translate internal labels' do
store_translations(:en, simple_form: { yes: 'Sim', no: 'Não' }) do
with_input_for @user, :active, :radio_buttons
assert_select 'label[for=user_active_true]', 'Sim'
assert_select 'label[for=user_active_false]', 'Não'
end
end
test 'input radio does not include for attribute by default' do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_select 'label'
assert_no_select 'label[for=user_gender]'
end
test 'input radio includes for attribute when giving as html option' do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female], label_html: { for: 'gender' }
assert_select 'label[for=gender]'
end
test 'input marks the checked value when using boolean and radios' do
@user.active = false
with_input_for @user, :active, :radio_buttons
assert_no_select 'input[type=radio][value=true][checked]'
assert_select 'input[type=radio][value=false][checked]'
end
test 'input allows overriding collection for radio types' do
with_input_for @user, :name, :radio_buttons, collection: %w[Jose Carlos]
assert_select 'input[type=radio][value=Jose]'
assert_select 'input[type=radio][value=Carlos]'
assert_select 'label.collection_radio_buttons[for=user_name_jose]', 'Jose'
assert_select 'label.collection_radio_buttons[for=user_name_carlos]', 'Carlos'
end
test 'input does automatic collection translation for radio types using defaults key' do
store_translations(:en, simple_form: { options: { defaults: {
gender: { male: 'Male', female: 'Female' }
} } } ) do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_select 'input[type=radio][value=male]'
assert_select 'input[type=radio][value=female]'
assert_select 'label.collection_radio_buttons[for=user_gender_male]', 'Male'
assert_select 'label.collection_radio_buttons[for=user_gender_female]', 'Female'
end
end
test 'input does automatic collection translation for radio types using specific object key' do
store_translations(:en, simple_form: { options: { user: {
gender: { male: 'Male', female: 'Female' }
} } } ) do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_select 'input[type=radio][value=male]'
assert_select 'input[type=radio][value=female]'
assert_select 'label.collection_radio_buttons[for=user_gender_male]', 'Male'
assert_select 'label.collection_radio_buttons[for=user_gender_female]', 'Female'
end
end
test 'input does automatic collection translation and preserve html markup' do
swap SimpleForm, boolean_style: :nested do
store_translations(:en, simple_form: { options: { user: {
gender: { male_html: '<strong>Male</strong>', female_html: '<strong>Female</strong>' }
} } } ) do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_select 'input[type=radio][value=male]'
assert_select 'input[type=radio][value=female]'
assert_select 'label[for=user_gender_male] strong', 'Male'
assert_select 'label[for=user_gender_female] strong', 'Female'
end
end
end
test 'input does automatic collection translation with keys prefixed with _html and a string value' do
swap SimpleForm, boolean_style: :nested do
store_translations(:en, simple_form: { options: { user: {
gender: { male_html: 'Male', female_html: 'Female' }
} } } ) do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_select 'input[type=radio][value=male]'
assert_select 'input[type=radio][value=female]'
assert_select 'label[for=user_gender_male]', 'Male'
assert_select 'label[for=user_gender_female]', 'Female'
end
end
end
test 'input marks the current radio value by default' do
@user.name = "Carlos"
with_input_for @user, :name, :radio_buttons, collection: %w[Jose Carlos]
assert_select 'input[type=radio][value=Carlos][checked=checked]'
end
test 'input accepts html options as the last element of collection' do
with_input_for @user, :name, :radio_buttons, collection: [['Jose', 'jose', class: 'foo']]
assert_select 'input.foo[type=radio][value=jose]'
end
test 'input allows using a collection with text/value arrays' do
with_input_for @user, :name, :radio_buttons, collection: [%w[Jose jose], %w[Carlos carlos]]
assert_select 'input[type=radio][value=jose]'
assert_select 'input[type=radio][value=carlos]'
assert_select 'label.collection_radio_buttons', 'Jose'
assert_select 'label.collection_radio_buttons', 'Carlos'
end
test 'input allows using a collection with a Proc' do
with_input_for @user, :name, :radio_buttons, collection: proc { %w[Jose Carlos] }
assert_select 'label.collection_radio_buttons', 'Jose'
assert_select 'label.collection_radio_buttons', 'Carlos'
end
test 'input allows overriding only label method for collections' do
with_input_for @user, :name, :radio_buttons,
collection: %w[Jose Carlos],
label_method: :upcase
assert_select 'label.collection_radio_buttons', 'JOSE'
assert_select 'label.collection_radio_buttons', 'CARLOS'
end
test 'input allows overriding only value method for collections' do
with_input_for @user, :name, :radio_buttons,
collection: %w[Jose Carlos],
value_method: :upcase
assert_select 'input[type=radio][value=JOSE]'
assert_select 'input[type=radio][value=CARLOS]'
end
test 'input allows overriding label and value method for collections' do
with_input_for @user, :name, :radio_buttons,
collection: %w[Jose Carlos],
label_method: :upcase,
value_method: :downcase
assert_select 'input[type=radio][value=jose]'
assert_select 'input[type=radio][value=carlos]'
assert_select 'label.collection_radio_buttons', 'JOSE'
assert_select 'label.collection_radio_buttons', 'CARLOS'
end
test 'input allows overriding label and value method using a lambda for collections' do
with_input_for @user, :name, :radio_buttons,
collection: %w[Jose Carlos],
label_method: ->(i) { i.upcase },
value_method: ->(i) { i.downcase }
assert_select 'input[type=radio][value=jose]'
assert_select 'input[type=radio][value=carlos]'
assert_select 'label.collection_radio_buttons', 'JOSE'
assert_select 'label.collection_radio_buttons', 'CARLOS'
end
test 'collection input with radio type generates required html attribute' do
with_input_for @user, :name, :radio_buttons, collection: %w[Jose Carlos]
assert_select 'input[type=radio].required'
assert_select 'input[type=radio][required]'
end
test 'input radio does not wrap the collection by default' do
with_input_for @user, :active, :radio_buttons
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
end
test 'input radio wraps the collection in the configured collection wrapper tag' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :radio_buttons
assert_select 'form ul input[type=radio]', count: 2
end
end
test 'input radio does not wrap the collection when configured with falsy values' do
swap SimpleForm, collection_wrapper_tag: false do
with_input_for @user, :active, :radio_buttons
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
end
end
test 'input radio allows overriding the collection wrapper tag at input level' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :radio_buttons, collection_wrapper_tag: :section
assert_select 'form section input[type=radio]', count: 2
assert_no_select 'form ul'
end
end
test 'input radio allows disabling the collection wrapper tag at input level' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :radio_buttons, collection_wrapper_tag: false
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form ul'
end
end
test 'input radio renders the wrapper tag with the configured wrapper class' do
swap SimpleForm, collection_wrapper_tag: :ul, collection_wrapper_class: 'inputs-list' do
with_input_for @user, :active, :radio_buttons
assert_select 'form ul.inputs-list input[type=radio]', count: 2
end
end
test 'input radio allows giving wrapper class at input level only' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :radio_buttons, collection_wrapper_class: 'items-list'
assert_select 'form ul.items-list input[type=radio]', count: 2
end
end
test 'input radio uses both configured and given wrapper classes for wrapper tag' do
swap SimpleForm, collection_wrapper_tag: :ul, collection_wrapper_class: 'inputs-list' do
with_input_for @user, :active, :radio_buttons, collection_wrapper_class: 'items-list'
assert_select 'form ul.inputs-list.items-list input[type=radio]', count: 2
end
end
test 'input radio wraps each item in the configured item wrapper tag' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :radio_buttons
assert_select 'form li input[type=radio]', count: 2
end
end
test 'input radio does not wrap items when configured with falsy values' do
swap SimpleForm, item_wrapper_tag: false do
with_input_for @user, :active, :radio_buttons
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form li'
end
end
test 'input radio allows overriding the item wrapper tag at input level' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :radio_buttons, item_wrapper_tag: :dl
assert_select 'form dl input[type=radio]', count: 2
assert_no_select 'form li'
end
end
test 'input radio allows disabling the item wrapper tag at input level' do
swap SimpleForm, item_wrapper_tag: :ul do
with_input_for @user, :active, :radio_buttons, item_wrapper_tag: false
assert_select 'form input[type=radio]', count: 2
assert_no_select 'form li'
end
end
test 'input radio wraps items in a span tag by default' do
with_input_for @user, :active, :radio_buttons
assert_select 'form span input[type=radio]', count: 2
end
test 'input radio renders the item wrapper tag with a default class "radio"' do
with_input_for @user, :active, :radio_buttons, item_wrapper_tag: :li
assert_select 'form li.radio input[type=radio]', count: 2
end
test 'input radio renders the item wrapper tag with the configured item wrapper class' do
swap SimpleForm, item_wrapper_tag: :li, item_wrapper_class: 'item' do
with_input_for @user, :active, :radio_buttons
assert_select 'form li.radio.item input[type=radio]', count: 2
end
end
test 'input radio allows giving item wrapper class at input level only' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :radio_buttons, item_wrapper_class: 'item'
assert_select 'form li.radio.item input[type=radio]', count: 2
end
end
test 'input radio uses both configured and given item wrapper classes for item wrapper tag' do
swap SimpleForm, item_wrapper_tag: :li, item_wrapper_class: 'item' do
with_input_for @user, :active, :radio_buttons, item_wrapper_class: 'inline'
assert_select 'form li.radio.item.inline input[type=radio]', count: 2
end
end
test 'input radio respects the nested boolean style config, generating nested label > input' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons
assert_select 'span.radio > label > input#user_active_true[type=radio]'
assert_select 'span.radio > label', 'Yes'
assert_select 'span.radio > label > input#user_active_false[type=radio]'
assert_select 'span.radio > label', 'No'
assert_no_select 'label.collection_radio_buttons'
end
end
test 'input radio with nested style does not overrides configured item wrapper tag' do
swap SimpleForm, boolean_style: :nested, item_wrapper_tag: :li do
with_input_for @user, :active, :radio_buttons
assert_select 'li.radio > label > input'
end
end
test 'input radio with nested style does not overrides given item wrapper tag' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons, item_wrapper_tag: :li
assert_select 'li.radio > label > input'
end
end
test 'input radio with nested style accepts giving extra wrapper classes' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons, item_wrapper_class: "inline"
assert_select 'span.radio.inline > label > input'
end
end
test 'input radio with nested style renders item labels with specified class' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :radio_buttons, item_label_class: "test"
assert_select 'span.radio > label.test > input'
end
end
test 'input radio with nested style and falsey input wrapper renders item labels with specified class' do
swap SimpleForm, boolean_style: :nested, item_wrapper_tag: false do
with_input_for @user, :active, :radio_buttons, item_label_class: "radio-inline"
assert_select 'label.radio-inline > input'
assert_no_select 'span.radio'
end
end
test 'input radio wrapper class are not included when set to falsey' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female]
assert_no_select 'label.radio'
end
end
test 'input radio custom wrapper class is included when include input wrapper class is falsey' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female], item_wrapper_class: 'custom'
assert_no_select 'label.radio'
assert_select 'span.custom'
end
end
test 'input radio with nested style and namespace uses the right for attribute' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_concat_form_for @user, namespace: :foo do |f|
concat f.input :gender, as: :radio_buttons, collection: %i[male female]
end
assert_select 'label[for=foo_user_gender_male]'
assert_select 'label[for=foo_user_gender_female]'
end
end
test 'input radio with nested style and index uses the right for attribute' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_concat_form_for @user, index: 1 do |f|
concat f.input :gender, as: :radio_buttons, collection: %i[male female]
end
assert_select 'label[for=user_1_gender_male]'
assert_select 'label[for=user_1_gender_female]'
end
end
test 'input radio with nested style accetps non-string attribute as label' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :amount,
:radio_buttons,
collection: { 100 => 'hundred', 200 => 'two_hundred' },
label_method: :first,
value_method: :second
assert_select 'input[type=radio][value=hundred]'
assert_select 'input[type=radio][value=two_hundred]'
assert_select 'span.radio > label', '100'
assert_select 'span.radio > label', '200'
end
end
test 'input check boxes with inline style support label custom classes' do
swap SimpleForm, boolean_style: :inline do
with_input_for @user, :gender, :radio_buttons, collection: %i[male female], item_label_class: 'beautiful-label'
assert_select 'label.beautiful-label', count: 2
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/datetime_input_test.rb | test/inputs/datetime_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
# Tests for datetime, date and time inputs when HTML5 compatibility is enabled in the wrapper.
class DateTimeInputWithHtml5Test < ActionView::TestCase
test 'input generates a datetime input for datetime attributes if HTML5 compatibility is explicitly enbled' do
with_input_for @user, :created_at, :datetime, html5: true
assert_select 'input[type="datetime-local"]'
end
test 'input generates a datetime select for datetime attributes' do
with_input_for @user, :created_at, :datetime
assert_select 'select.datetime'
end
test 'input generates a date input for date attributes if HTML5 compatibility is explicitly enbled' do
with_input_for @user, :born_at, :date, html5: true
assert_select 'input[type="date"]'
end
test 'input generates a date select for date attributes' do
with_input_for @user, :born_at, :date
assert_select 'select.date'
end
test 'input generates a time input for time attributes if HTML5 compatibility is explicitly enbled' do
with_input_for @user, :delivery_time, :time, html5: true
assert_select 'input[type="time"]'
end
test 'input generates a time select for time attributes' do
with_input_for @user, :delivery_time, :time
assert_select 'select.time'
end
test 'input generates required html attribute' do
with_input_for @user, :delivery_time, :time, required: true, html5: true
assert_select 'input.required'
assert_select 'input[required]'
end
end
# Tests for datetime, date and time inputs when HTML5 compatibility is enabled in the wrapper.
class DateTimeInputWithoutHtml5Test < ActionView::TestCase
test 'input generates a datetime select by default for datetime attributes' do
swap_wrapper do
with_input_for @user, :created_at, :datetime
1.upto(5) do |i|
assert_select "form select.datetime#user_created_at_#{i}i"
end
end
end
test 'input is able to pass options to datetime select' do
with_input_for @user, :created_at, :datetime, html5: false,
disabled: true, prompt: { year: 'ano', month: 'mês', day: 'dia' }
assert_select 'select.datetime[disabled=disabled]'
assert_select 'select.datetime option', 'ano'
assert_select 'select.datetime option', 'mês'
assert_select 'select.datetime option', 'dia'
end
test 'input generates a datetime input for datetime attributes if HTML5 compatibility is explicitly enabled' do
swap_wrapper do
with_input_for @user, :created_at, :datetime, html5: true
assert_select 'input[type="datetime-local"]'
end
end
test 'input generates a date select for date attributes' do
swap_wrapper do
with_input_for @user, :born_at, :date
assert_select 'select.date#user_born_at_1i'
assert_select 'select.date#user_born_at_2i'
assert_select 'select.date#user_born_at_3i'
assert_no_select 'select.date#user_born_at_4i'
end
end
test 'input is able to pass options to date select' do
with_input_for @user, :born_at, :date, as: :date, html5: false,
disabled: true, prompt: { year: 'ano', month: 'mês', day: 'dia' }
assert_select 'select.date[disabled=disabled]'
assert_select 'select.date option', 'ano'
assert_select 'select.date option', 'mês'
assert_select 'select.date option', 'dia'
end
test 'input is able to pass :default to date select' do
with_input_for @user, :born_at, :date, default: Date.today, html5: false
assert_select "select.date option[value='#{Date.today.year}'][selected=selected]"
end
test 'input generates a date input for date attributes if HTML5 compatibility is explicitly enabled' do
swap_wrapper do
with_input_for @user, :born_at, :date, html5: true
assert_select 'input[type="date"]'
end
end
test 'input generates a time select for time attributes' do
swap_wrapper do
with_input_for @user, :delivery_time, :time
assert_select 'input[type=hidden]#user_delivery_time_1i'
assert_select 'input[type=hidden]#user_delivery_time_2i'
assert_select 'input[type=hidden]#user_delivery_time_3i'
assert_select 'select.time#user_delivery_time_4i'
assert_select 'select.time#user_delivery_time_5i'
end
end
test 'input is able to pass options to time select' do
with_input_for @user, :delivery_time, :time, required: true, html5: false,
disabled: true, prompt: { hour: 'hora', minute: 'minuto' }
assert_select 'select.time[disabled=disabled]'
assert_select 'select.time option', 'hora'
assert_select 'select.time option', 'minuto'
end
test 'input generates a time input for time attributes if HTML5 compatibility is explicitly enabled' do
swap_wrapper do
with_input_for @user, :delivery_time, :time, html5: true
assert_select 'input[type="time"]'
end
end
test 'label uses i18n to get target for date input type' do
store_translations(:en, date: { order: %w[month day year] }) do
with_input_for :project, :created_at, :date, html5: false
assert_select 'label[for=project_created_at_2i]'
end
end
test 'label uses i18n to get target for datetime input type' do
store_translations(:en, date: { order: %w[month day year] }) do
with_input_for :project, :created_at, :datetime, html5: false
assert_select 'label[for=project_created_at_2i]'
end
end
test 'label uses order to get target when date input type' do
with_input_for :project, :created_at, :date, order: %w[month year day], html5: false
assert_select 'label[for=project_created_at_2i]'
end
test 'label uses order to get target when datetime input type' do
with_input_for :project, :created_at, :datetime, order: %w[month year day], html5: false
assert_select 'label[for=project_created_at_2i]'
end
test 'label points to first option when time input type' do
with_input_for :project, :created_at, :time, html5: false
assert_select 'label[for=project_created_at_4i]'
end
test 'label points to attribute name if HTML5 compatibility is explicitly enabled' do
with_input_for :project, :created_at, :date, html5: true
assert_select 'label[for=project_created_at]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/file_input_test.rb | test/inputs/file_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class FileInputTest < ActionView::TestCase
test 'input generates a file field' do
with_input_for @user, :name, :file
assert_select 'input#user_name[type=file]'
end
test "input generates a file field that doesn't accept placeholder" do
store_translations(:en, simple_form: { placeholders: { user: { name: "text" } } }) do
with_input_for @user, :name, :file
assert_no_select 'input[placeholder]'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/general_test.rb | test/inputs/general_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class InputTest < ActionView::TestCase
test 'input generates css class based on default input type' do
with_input_for @user, :name, :string
assert_select 'input.string'
with_input_for @user, :description, :text
assert_select 'textarea.text'
with_input_for @user, :age, :integer
assert_select 'input.integer'
with_input_for @user, :born_at, :date
assert_select 'select.date'
with_input_for @user, :created_at, :datetime
assert_select 'select.datetime'
end
test 'string input generates autofocus attribute when autofocus option is true' do
with_input_for @user, :name, :string, autofocus: true
assert_select 'input.string[autofocus]'
end
test 'input accepts input_class configuration' do
swap SimpleForm, input_class: :xlarge do
with_input_for @user, :name, :string
assert_select 'input.xlarge'
assert_no_select 'div.xlarge'
end
end
test 'input does not add input_class when configured to not generate additional classes for input' do
swap SimpleForm, input_class: 'xlarge', generate_additional_classes_for: [:wrapper] do
with_input_for @user, :name, :string
assert_select 'input'
assert_no_select '.xlarge'
end
end
test 'text input generates autofocus attribute when autofocus option is true' do
with_input_for @user, :description, :text, autofocus: true
assert_select 'textarea.text[autofocus]'
end
test 'numeric input generates autofocus attribute when autofocus option is true' do
with_input_for @user, :age, :integer, autofocus: true
assert_select 'input.integer[autofocus]'
end
test 'date input generates autofocus attribute when autofocus option is true' do
with_input_for @user, :born_at, :date, autofocus: true
assert_select 'select.date[autofocus]'
end
test 'datetime input generates autofocus attribute when autofocus option is true' do
with_input_for @user, :created_at, :datetime, autofocus: true
assert_select 'select.datetime[autofocus]'
end
test 'string input generates autofocus attribute when autofocus option is false' do
with_input_for @user, :name, :string, autofocus: false
assert_no_select 'input.string[autofocus]'
end
test 'text input generates autofocus attribute when autofocus option is false' do
with_input_for @user, :description, :text, autofocus: false
assert_no_select 'textarea.text[autofocus]'
end
test 'numeric input generates autofocus attribute when autofocus option is false' do
with_input_for @user, :age, :integer, autofocus: false
assert_no_select 'input.integer[autofocus]'
end
test 'date input generates autofocus attribute when autofocus option is false' do
with_input_for @user, :born_at, :date, autofocus: false
assert_no_select 'select.date[autofocus]'
end
test 'datetime input generates autofocus attribute when autofocus option is false' do
with_input_for @user, :created_at, :datetime, autofocus: false
assert_no_select 'select.datetime[autofocus]'
end
test 'string input generates autofocus attribute when autofocus option is not present' do
with_input_for @user, :name, :string
assert_no_select 'input.string[autofocus]'
end
test 'text input generates autofocus attribute when autofocus option is not present' do
with_input_for @user, :description, :text
assert_no_select 'textarea.text[autofocus]'
end
test 'numeric input generates autofocus attribute when autofocus option is not present' do
with_input_for @user, :age, :integer
assert_no_select 'input.integer[autofocus]'
end
test 'date input generates autofocus attribute when autofocus option is not present' do
with_input_for @user, :born_at, :date
assert_no_select 'select.date[autofocus]'
end
test 'datetime input generates autofocus attribute when autofocus option is not present' do
with_input_for @user, :created_at, :datetime
assert_no_select 'select.datetime[autofocus]'
end
# With no object
test 'input is generated properly when object is not present' do
with_input_for :project, :name, :string
assert_select 'input.string.required#project_name'
end
test 'input as radio is generated properly when object is not present ' do
with_input_for :project, :name, :radio_buttons
assert_select 'input.radio_buttons#project_name_true'
assert_select 'input.radio_buttons#project_name_false'
end
test 'input as select with collection is generated properly when object is not present' do
with_input_for :project, :name, :select, collection: %w[Jose Carlos]
assert_select 'select.select#project_name'
end
test 'input does not generate empty css class' do
swap SimpleForm, generate_additional_classes_for: %i[wrapper label] do
with_input_for :project, :name, :string
assert_no_select 'input#project_name[class]'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/boolean_input_test.rb | test/inputs/boolean_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class BooleanInputTest < ActionView::TestCase
test 'input generates a checkbox by default for boolean attributes' do
with_input_for @user, :active, :boolean
assert_select 'input[type=checkbox].boolean#user_active'
assert_select 'label.boolean.optional', 'Active'
end
test 'input does not generate the label with the checkbox when label option is false' do
with_input_for @user, :active, :boolean, label: false
assert_select 'input[type=checkbox].boolean#user_active'
assert_no_select 'label'
end
test 'input uses custom checked value' do
@user.action = 'on'
with_input_for @user, :action, :boolean, checked_value: 'on', unchecked_value: 'off'
assert_select 'input[type=checkbox][value=on][checked=checked]'
end
test 'input uses custom unchecked value' do
@user.action = 'off'
with_input_for @user, :action, :boolean, checked_value: 'on', unchecked_value: 'off'
assert_select 'input[type=checkbox][value=on]'
assert_no_select 'input[checked=checked][value=on]'
end
test 'input generates hidden input with custom unchecked value' do
with_input_for @user, :action, :boolean, checked_value: 'on', unchecked_value: 'off'
assert_select 'input[type=hidden][value=off]'
end
test 'input allows skipping hidden input when setting :include_hidden to false' do
with_input_for @user, :active, :boolean, include_hidden: false
assert_no_select "input[type=hidden][name='user[active]']"
end
test 'input uses inline boolean style by default' do
with_input_for @user, :active, :boolean
assert_select 'input.boolean + label.boolean.optional'
assert_no_select 'label > input'
end
test 'input allows changing default boolean style config to nested, generating a default label and a manual hidden field for checkbox' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean
assert_select 'label[for=user_active]', 'Active'
assert_select 'label.boolean > input.boolean'
assert_no_select 'input[type=checkbox] + label'
end
end
test 'input boolean with nested allows :inline_label' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: 'I am so inline.'
assert_select 'label.checkbox', text: ' I am so inline.'
end
end
test 'input boolean with nested escapes :inline_label with HTML' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: '<b>I am so inline.</b>'
assert_no_select 'label.checkbox b'
end
end
test 'input boolean with nested allows :inline_label with HTML when safe' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: '<b>I am so inline.</b>'.html_safe
assert_select 'label.checkbox b', text: 'I am so inline.'
end
end
test 'input boolean with nested style creates an inline label using the default label text when inline_label option set to true' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: true
assert_select 'label.checkbox', text: ' Active'
end
end
test 'input boolean with nested style creates an inline label using the label text when inline_label option set to true' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: true, label_text: proc { 'New Active' }
assert_select 'label.checkbox', text: ' New Active'
end
end
test 'input boolean with nested style creates an inline label using the label html when inline_label option set to true' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, inline_label: true, label_text: proc { '<b>New Active</b>' }
assert_select 'label.checkbox', text: ' New Active'
end
end
test 'input boolean with nested generates a manual hidden field for checkbox outside the label, to recreate Rails functionality with valid html5' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean
assert_select "input[type=hidden][name='user[active]'] + label.boolean > input.boolean"
assert_no_select 'input[type=checkbox] + label'
end
end
test 'input boolean with nested generates a disabled hidden field for checkbox outside the label, if the field is disabled' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, disabled: true
assert_select "input[type=hidden][name='user[active]'][disabled] + label.boolean > input.boolean[disabled]"
end
end
test 'input boolean with nested generates a disabled hidden field with the form attribute when it is given' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, input_html: { form: 'form_id' }
assert_select "input[type=hidden][form=form_id]+ label.boolean > input.boolean"
end
end
test 'input accepts changing boolean style to nested through given options' do
with_input_for @user, :active, :boolean, boolean_style: :nested
assert_select 'label[for=user_active]', 'Active'
assert_select 'label.boolean > input.boolean'
assert_no_select 'input[type=checkbox] + label'
end
test 'input accepts changing boolean style to inline through given options, when default is nested' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, boolean_style: :inline
assert_select 'label[for=user_active]', 'Active'
assert_select 'input.boolean + label.boolean'
assert_no_select 'label > input'
end
end
test 'input with nested style allows disabling label' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, label: false
assert_select 'input.boolean'
assert_no_select 'label.boolean'
end
end
test 'input with nested style allows customizing input_html' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, input_html: { name: 'active_user' }
assert_select "input[type=hidden][name=active_user] + label.boolean > input.boolean[name=active_user]"
end
end
test 'input with nested style allows disabling hidden field' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, include_hidden: false
assert_select "label.boolean > input.boolean"
assert_no_select "input[type=hidden] + label.boolean"
end
end
test 'input with nested style and with single wrapper allows disabling hidden field' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, include_hidden: false, wrapper: custom_wrapper_with_wrapped_label_input
assert_select "label.boolean > input.boolean"
assert_no_select "input[type=hidden] + label.boolean"
end
end
test 'input with nested style does not include hidden field when unchecked_value is false' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean, unchecked_value: false
assert_select "label.boolean > input.boolean"
assert_no_select "input[type=hidden] + label.boolean"
end
end
test 'input boolean works using :input only in wrapper config (no label_input)' do
swap_wrapper do
with_input_for @user, :active, :boolean
assert_select 'label.boolean + input[type=hidden] + input.boolean'
assert_no_select 'label.checkbox'
end
end
test 'input boolean with nested style works using :input only in wrapper config (no label_input), adding the extra "checkbox" label wrapper' do
swap_wrapper do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean
assert_select 'label.boolean + input[type=hidden] + label.checkbox > input.boolean'
end
end
end
test 'input boolean allows specifying boolean_label_class on a per-input basis' do
swap_wrapper do
swap SimpleForm, boolean_style: :nested, boolean_label_class: 'foo' do
with_input_for @user, :active, :boolean, boolean_label_class: 'baz'
assert_select 'label.boolean + input[type=hidden] + label.baz > input.boolean'
end
end
end
test 'input boolean with nested style works using :input only in wrapper config (no label_input), adding the extra label wrapper with custom class' do
swap_wrapper do
swap SimpleForm, boolean_style: :nested, boolean_label_class: 'foo' do
with_input_for @user, :active, :boolean
assert_select 'label.boolean + input[type=hidden] + label.foo > input.boolean'
end
end
end
test 'input boolean with nested style works using :label_input in wrapper config, adding "checkbox" class to label' do
swap_wrapper :default, self.custom_wrapper_without_top_level do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :boolean
assert_select 'input[type=hidden] + label.boolean.checkbox > input.boolean'
end
end
end
test 'input boolean with nested style works using :label_input in wrapper config, adding custom class to label' do
swap_wrapper :default, self.custom_wrapper_without_top_level do
swap SimpleForm, boolean_style: :nested, boolean_label_class: 'foo' do
with_input_for @user, :active, :boolean
assert_select 'input[type=hidden] + label.boolean.foo > input.boolean'
end
end
end
test 'input boolean without additional classes adds "checkbox" class to label' do
swap_wrapper :default, self.custom_wrapper_without_top_level do
swap SimpleForm, boolean_style: :nested, generate_additional_classes_for: [:input] do
with_input_for @user, :active, :boolean
assert_select 'label'
assert_select 'label.checkbox'
assert_no_select 'label.boolean'
end
end
end
test 'input boolean works with wrapper config defining a class for the input' do
swap_wrapper :default, self.custom_wrapper_with_input_class do
with_input_for @user, :active, :boolean
assert_select 'input.boolean.inline-class'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/grouped_collection_select_input_test.rb | test/inputs/grouped_collection_select_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class GroupedCollectionSelectInputTest < ActionView::TestCase
test 'grouped collection accepts array collection form' do
with_input_for @user, :tag_ids, :grouped_select,
collection: [['Authors', %w[Jose Carlos]], ['General', %w[Bob John]]],
group_method: :last
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option', 'Jose'
assert_select 'option', 'Carlos'
end
assert_select 'optgroup[label=General]' do
assert_select 'option', 'Bob'
assert_select 'option', 'John'
end
end
end
test 'grouped collection accepts empty array collection form' do
with_input_for @user, :tag_ids, :grouped_select,
collection: [],
group_method: :last
assert_select 'select.grouped_select#user_tag_ids'
end
test 'grouped collection accepts proc as collection' do
with_input_for @user, :tag_ids, :grouped_select,
collection: proc { [['Authors', %w[Jose Carlos]], ['General', %w[Bob John]]] },
group_method: :last
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option', 'Jose'
assert_select 'option', 'Carlos'
end
assert_select 'optgroup[label=General]' do
assert_select 'option', 'Bob'
assert_select 'option', 'John'
end
end
end
test 'grouped collection accepts hash collection form' do
with_input_for @user, :tag_ids, :grouped_select,
collection: { Authors: %w[Jose Carlos], General: %w[Bob John] },
group_method: :last
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option', 'Jose'
assert_select 'option', 'Carlos'
end
assert_select 'optgroup[label=General]' do
assert_select 'option', 'Bob'
assert_select 'option', 'John'
end
end
end
test 'grouped collection allows overriding group_method using a lambda' do
with_input_for @user, :tag_ids, :grouped_select,
collection: { Authors: %w[Jose Carlos] },
group_method: ->(i) { i.last }
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option[value=Jose]', 'Jose'
assert_select 'option[value=Carlos]', 'Carlos'
end
end
end
test 'grouped collection accepts group_label_method option' do
with_input_for @user, :tag_ids, :grouped_select,
collection: { %w[Jose Carlos] => 'Authors' },
group_method: :first,
group_label_method: :last
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option', 'Jose'
assert_select 'option', 'Carlos'
end
end
end
test 'grouped collection finds default label methods on the group objects' do
option_list = %w[Jose Carlos]
GroupedClass = Struct.new(:to_label, :options)
group = GroupedClass.new("Authors", option_list)
with_input_for @user, :tag_ids, :grouped_select,
collection: [group],
group_method: :options
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option', 'Jose'
assert_select 'option', 'Carlos'
end
end
end
test 'grouped collections finds the default label method from the first non-empty object' do
Agent = Struct.new(:id, :name)
agents = [["First", []], ["Second", [Agent.new(7, 'Bond'), Agent.new(47, 'Hitman')]]]
with_input_for @user, :tag_ids, :grouped_select,
collection: agents,
group_label_method: :first,
group_method: :last,
include_blank: false
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Second]' do
assert_select 'option[value="7"]', 'Bond'
assert_select 'option[value="47"]', 'Hitman'
end
end
end
test 'grouped collection accepts label and value methods options' do
with_input_for @user, :tag_ids, :grouped_select,
collection: { Authors: %w[Jose Carlos] },
group_method: :last,
label_method: :upcase,
value_method: :downcase
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option[value=jose]', 'JOSE'
assert_select 'option[value=carlos]', 'CARLOS'
end
end
end
test 'grouped collection allows overriding label and value methods using a lambda' do
with_input_for @user, :tag_ids, :grouped_select,
collection: { Authors: %w[Jose Carlos] },
group_method: :last,
label_method: ->(i) { i.upcase },
value_method: ->(i) { i.downcase }
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option[value=jose]', 'JOSE'
assert_select 'option[value=carlos]', 'CARLOS'
end
end
end
test 'grouped collection with associations' do
tag_groups = [
TagGroup.new(1, "Group of Tags", [Tag.new(1, "Tag 1"), Tag.new(2, "Tag 2")]),
TagGroup.new(2, "Other group", [Tag.new(3, "Tag 3"), Tag.new(4, "Tag 4")])
]
with_input_for @user, :tag_ids, :grouped_select,
collection: tag_groups, group_method: :tags
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label="Group of Tags"]' do
assert_select 'option[value="1"]', 'Tag 1'
assert_select 'option[value="2"]', 'Tag 2'
end
assert_select 'optgroup[label="Other group"]' do
assert_select 'option[value="3"]', 'Tag 3'
assert_select 'option[value="4"]', 'Tag 4'
end
end
end
test 'grouped collection accepts html options as the last element of collection' do
with_input_for @user, :tag_ids, :grouped_select,
collection: [['Authors', [['Jose', 'jose', class: 'foo'], ['Carlos', 'carlos', class: 'bar']]]],
group_method: :last
assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Authors]' do
assert_select 'option.foo', 'Jose'
assert_select 'option.bar', 'Carlos'
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/required_test.rb | test/inputs/required_test.rb | # frozen_string_literal: true
require 'test_helper'
class RequiredTest < ActionView::TestCase
# REQUIRED AND PRESENCE VALIDATION
test 'builder input obtains required from ActiveModel::Validations when it is included' do
with_form_for @validating_user, :name
assert_select 'input.required[required]#validating_user_name'
with_form_for @validating_user, :status
assert_select 'input.optional#validating_user_status'
end
test 'builder input allows overriding required when ActiveModel::Validations is included' do
with_form_for @validating_user, :name, required: false
assert_select 'input.optional#validating_user_name'
with_form_for @validating_user, :status, required: true
assert_select 'input.required[required]#validating_user_status'
end
test 'builder input is required by default when ActiveModel::Validations is not included' do
with_form_for @user, :name
assert_select 'input.required[required]#user_name'
end
test 'builder input does not be required by default when ActiveModel::Validations is not included if option is set to false' do
swap SimpleForm, required_by_default: false do
with_form_for @user, :name
assert_select 'input.optional#user_name'
assert_no_select 'input[required]'
end
end
test 'when not using browser validations, input does not generate required html attribute' do
swap SimpleForm, browser_validations: false do
with_input_for @user, :name, :string
assert_select 'input[type=text].required'
assert_no_select 'input[type=text][required]'
end
end
test 'when not using browser validations, when required option is set to false, input does not generate required html attribute' do
swap SimpleForm, browser_validations: false do
with_input_for @user, :name, :string, required: false
assert_no_select 'input[type=text].required'
assert_no_select 'input[type=text][required]'
end
end
test 'when not using browser validations, when required option is set to true, input generates required html attribute' do
swap SimpleForm, browser_validations: false do
with_input_for @user, :name, :string, required: true
assert_select 'input[type=text].required'
assert_select 'input[type=text][required]'
end
end
test 'when not using browser validations, when required option is true in the wrapper, input does not generate required html attribute' do
swap SimpleForm, browser_validations: false do
swap_wrapper :default, self.custom_wrapper_with_required_input do
with_concat_form_for(@user) do |f|
concat f.input :name
end
assert_select 'input[type=text].required'
assert_no_select 'input[type=text][required]'
end
end
end
test 'builder input allows disabling required when ActiveModel::Validations is not included' do
with_form_for @user, :name, required: false
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#user_name'
end
test 'when not the required component the input does not have the required attribute but has the required class' do
swap_wrapper do
with_input_for @user, :name, :string
assert_select 'input[type=text].required'
assert_no_select 'input[type=text][required]'
end
end
# VALIDATORS :if :unless
test 'builder input does not be required when ActiveModel::Validations is included and if option is present' do
with_form_for @validating_user, :age
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#validating_user_age'
end
test 'builder input does not be required when ActiveModel::Validations is included and unless option is present' do
with_form_for @validating_user, :amount
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#validating_user_amount'
end
# VALIDATORS :on
test 'builder input is required when validation is on create and is not persisted' do
@validating_user.new_record!
with_form_for @validating_user, :action
assert_select 'input.required'
assert_select 'input[required]'
assert_select 'input.required[required]#validating_user_action'
end
test 'builder input does not be required when validation is on create and is persisted' do
with_form_for @validating_user, :action
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#validating_user_action'
end
test 'builder input is required when validation is on save' do
with_form_for @validating_user, :credit_limit
assert_select 'input.required'
assert_select 'input[required]'
assert_select 'input.required[required]#validating_user_credit_limit'
@validating_user.new_record!
with_form_for @validating_user, :credit_limit
assert_select 'input.required'
assert_select 'input[required]'
assert_select 'input.required[required]#validating_user_credit_limit'
end
test 'builder input is required when validation is on update and is persisted' do
with_form_for @validating_user, :phone_number
assert_select 'input.required'
assert_select 'input[required]'
assert_select 'input.required[required]#validating_user_phone_number'
end
test 'builder input does not be required when validation is on update and is not persisted' do
@validating_user.new_record!
with_form_for @validating_user, :phone_number
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_select 'input.optional#validating_user_phone_number'
end
test 'builder input does not generate required html attribute when option is set to false when it is set to true in wrapper' do
swap SimpleForm, browser_validations: true do
swap_wrapper :default, self.custom_wrapper_with_required_input do
with_concat_form_for(@user) do |f|
concat f.input :name, required: false
end
assert_no_select 'input[type=text][required]'
end
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/readonly_test.rb | test/inputs/readonly_test.rb | # frozen_string_literal: true
require 'test_helper'
class ReadonlyTest < ActionView::TestCase
test 'string input generates readonly elements when readonly option is true' do
with_input_for @user, :name, :string, readonly: true
assert_select 'input.string.readonly[readonly]'
end
test 'text input generates readonly elements when readonly option is true' do
with_input_for @user, :description, :text, readonly: true
assert_select 'textarea.text.readonly[readonly]'
end
test 'numeric input generates readonly elements when readonly option is true' do
with_input_for @user, :age, :integer, readonly: true
assert_select 'input.integer.readonly[readonly]'
end
test 'date input generates readonly elements when readonly option is true' do
with_input_for @user, :born_at, :date, readonly: true
assert_select 'select.date.readonly[readonly]'
end
test 'datetime input generates readonly elements when readonly option is true' do
with_input_for @user, :created_at, :datetime, readonly: true
assert_select 'select.datetime.readonly[readonly]'
end
test 'string input generates readonly elements when readonly option is false' do
with_input_for @user, :name, :string, readonly: false
assert_no_select 'input.string.readonly[readonly]'
end
test 'text input generates readonly elements when readonly option is false' do
with_input_for @user, :description, :text, readonly: false
assert_no_select 'textarea.text.readonly[readonly]'
end
test 'numeric input generates readonly elements when readonly option is false' do
with_input_for @user, :age, :integer, readonly: false
assert_no_select 'input.integer.readonly[readonly]'
end
test 'date input generates readonly elements when readonly option is false' do
with_input_for @user, :born_at, :date, readonly: false
assert_no_select 'select.date.readonly[readonly]'
end
test 'datetime input generates readonly elements when readonly option is false' do
with_input_for @user, :created_at, :datetime, readonly: false
assert_no_select 'select.datetime.readonly[readonly]'
end
test 'string input generates readonly elements when readonly option is not present' do
with_input_for @user, :name, :string
assert_no_select 'input.string.readonly[readonly]'
end
test 'text input generates readonly elements when readonly option is not present' do
with_input_for @user, :description, :text
assert_no_select 'textarea.text.readonly[readonly]'
end
test 'numeric input generates readonly elements when readonly option is not present' do
with_input_for @user, :age, :integer
assert_no_select 'input.integer.readonly[readonly]'
end
test 'date input generates readonly elements when readonly option is not present' do
with_input_for @user, :born_at, :date
assert_no_select 'select.date.readonly[readonly]'
end
test 'datetime input generates readonly elements when readonly option is not present' do
with_input_for @user, :created_at, :datetime
assert_no_select 'select.datetime.readonly[readonly]'
end
test 'input generates readonly attribute when the field is readonly and the object is persisted' do
with_input_for @user, :credit_card, :string, readonly: :lookup
assert_select 'input.string.readonly[readonly]'
end
test 'input does not generate readonly attribute when the field is readonly and the object is not persisted' do
@user.new_record!
with_input_for @user, :credit_card, :string, readonly: :lookup
assert_no_select 'input.string.readonly[readonly]'
end
test 'input does not generate readonly attribute when the field is not readonly and the object is persisted' do
with_input_for @user, :name, :string
assert_no_select 'input.string.readonly[readonly]'
end
test 'input does not generate readonly attribute when the component is not used' do
swap_wrapper do
with_input_for @user, :credit_card, :string
assert_no_select 'input.string.readonly[readonly]'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/string_input_test.rb | test/inputs/string_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class StringInputTest < ActionView::TestCase
test 'input maps text field to string attribute' do
with_input_for @user, :name, :string
assert_select "input#user_name[type=text][name='user[name]'][value='New in SimpleForm!']"
end
test 'input maps text field to citext attribute' do
with_input_for @user, :name, :citext
assert_select "input#user_name[type=text][name='user[name]'][value='New in SimpleForm!']"
end
test 'input generates a password field for password attributes' do
with_input_for @user, :password, :password
assert_select "input#user_password.password[type=password][name='user[password]']"
end
test 'input gets maxlength from column definition for string attributes' do
with_input_for @user, :name, :string
assert_select 'input.string[maxlength="100"]'
end
test 'input does not get maxlength from column without size definition for string attributes' do
with_input_for @user, :action, :string
assert_no_select 'input.string[maxlength]'
end
test 'input gets maxlength from column definition for password attributes' do
with_input_for @user, :password, :password
assert_select 'input.password[type=password][maxlength="100"]'
end
test 'input infers maxlength column definition from validation when present' do
with_input_for @validating_user, :name, :string
assert_select 'input.string[maxlength="25"]'
end
test 'input infers minlength column definition from validation when present' do
with_input_for @validating_user, :name, :string
assert_select 'input.string[minlength="5"]'
end
test 'input gets maxlength from validation when :is option present' do
with_input_for @validating_user, :home_picture, :string
assert_select 'input.string[maxlength="12"]'
end
test 'input gets minlength from validation when :is option present' do
with_input_for @validating_user, :home_picture, :string
assert_select 'input.string[minlength="12"]'
end
test 'input maxlength is the column limit plus one to make room for decimal point' do
with_input_for @user, :credit_limit, :string
assert_select 'input.string[maxlength="16"]'
end
test 'input does not generate placeholder by default' do
with_input_for @user, :name, :string
assert_no_select 'input[placeholder]'
end
test 'input accepts the placeholder option' do
with_input_for @user, :name, :string, placeholder: 'Put in some text'
assert_select 'input.string[placeholder="Put in some text"]'
end
test 'input generates a password field for password attributes that accept placeholder' do
with_input_for @user, :password, :password, placeholder: 'Password Confirmation'
assert_select 'input[type=password].password[placeholder="Password Confirmation"]#user_password'
end
test 'input does not infer pattern from attributes by default' do
with_input_for @other_validating_user, :country, :string
assert_no_select 'input[pattern="\w+"]'
end
test 'input infers pattern from attributes' do
with_input_for @other_validating_user, :country, :string, pattern: true
assert_select "input:match('pattern', ?)", /\w+/
end
test 'input infers pattern from attributes using proc' do
with_input_for @other_validating_user, :name, :string, pattern: true
assert_select "input:match('pattern', ?)", /\w+/
end
test 'input does not infer pattern from attributes if root default is false' do
swap_wrapper do
with_input_for @other_validating_user, :country, :string
assert_no_select 'input[pattern="\w+"]'
end
end
test 'input uses given pattern from attributes' do
with_input_for @other_validating_user, :country, :string, input_html: { pattern: "\\d+" }
assert_select "input:match('pattern', ?)", /\\d+/
end
test 'input does not use pattern if model has :without validation option' do
with_input_for @other_validating_user, :description, :string, pattern: true
assert_no_select 'input[pattern="\d+"]'
end
test 'input uses i18n to translate placeholder text' do
store_translations(:en, simple_form: { placeholders: { user: {
name: 'Name goes here'
} } }) do
with_input_for @user, :name, :string
assert_select 'input.string[placeholder="Name goes here"]'
end
end
test 'input uses custom i18n scope to translate placeholder text' do
store_translations(:en, my_scope: { placeholders: { user: {
name: 'Name goes here'
} } }) do
swap SimpleForm, i18n_scope: :my_scope do
with_input_for @user, :name, :string
assert_select 'input.string[placeholder="Name goes here"]'
end
end
end
%i[email url search tel].each do |type|
test "input allows type #{type}" do
with_input_for @user, :name, type
assert_select "input.string.#{type}"
assert_select "input[type=#{type}]"
end
test "input does not allow type #{type} if HTML5 compatibility is disabled" do
swap_wrapper do
with_input_for @user, :name, type
assert_select "input[type=text]"
assert_no_select "input[type=#{type}]"
end
end
end
test 'input strips extra spaces from class html attribute with default classes' do
with_input_for @user, :name, :string
assert_select "input[class='string required']"
assert_no_select "input[class='string required ']"
assert_no_select "input[class=' string required']"
end
test 'input strips extra spaces from class html attribute when giving a custom class' do
with_input_for @user, :name, :string, input_html: { class: "my_input" }
assert_select "input[class='string required my_input']"
assert_no_select "input[class='string required my_input ']"
assert_no_select "input[class=' string required my_input']"
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/collection_select_input_test.rb | test/inputs/collection_select_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class CollectionSelectInputTest < ActionView::TestCase
test 'input generates a boolean select with options by default for select types' do
with_input_for @user, :active, :select
assert_select 'select.select#user_active'
assert_select 'select option[value=true]', 'Yes'
assert_select 'select option[value=false]', 'No'
end
test 'input as select uses i18n to translate select boolean options' do
store_translations(:en, simple_form: { yes: 'Sim', no: 'Não' }) do
with_input_for @user, :active, :select
assert_select 'select option[value=true]', 'Sim'
assert_select 'select option[value=false]', 'Não'
end
end
test 'input allows overriding collection for select types' do
with_input_for @user, :name, :select, collection: %w[Jose Carlos]
assert_select 'select.select#user_name'
assert_select 'select option', 'Jose'
assert_select 'select option', 'Carlos'
end
test 'input does automatic collection translation for select types using defaults key' do
store_translations(:en, simple_form: { options: { defaults: {
gender: { male: 'Male', female: 'Female' }
} } }) do
with_input_for @user, :gender, :select, collection: %i[male female]
assert_select 'select.select#user_gender'
assert_select 'select option', 'Male'
assert_select 'select option', 'Female'
end
end
test 'input does automatic collection translation for select types using specific object key' do
store_translations(:en, simple_form: { options: { user: {
gender: { male: 'Male', female: 'Female' }
} } }) do
with_input_for @user, :gender, :select, collection: %i[male female]
assert_select 'select.select#user_gender'
assert_select 'select option', 'Male'
assert_select 'select option', 'Female'
end
end
test 'input marks the selected value by default' do
@user.name = "Carlos"
with_input_for @user, :name, :select, collection: %w[Jose Carlos]
assert_select 'select option[selected=selected]', 'Carlos'
end
test 'input accepts html options as the last element of collection' do
with_input_for @user, :name, :select, collection: [['Jose', class: 'foo']]
assert_select 'select.select#user_name'
assert_select 'select option.foo', 'Jose'
end
test 'input marks the selected value also when using integers' do
@user.age = 18
with_input_for @user, :age, :select, collection: 18..60
assert_select 'select option[selected=selected]', '18'
end
test 'input marks the selected value when using booleans and select' do
@user.active = false
with_input_for @user, :active, :select
assert_no_select 'select option[selected][value=true]', 'Yes'
assert_select 'select option[selected][value=false]', 'No'
end
test 'input sets the correct value when using a collection that includes floats' do
with_input_for @user, :age, :select, collection: [2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
assert_select 'select option[value="2.0"]'
assert_select 'select option[value="2.5"]'
end
test 'input sets the correct values when using a collection that uses mixed values' do
with_input_for @user, :age, :select, collection: ["Hello Kitty", 2, 4.5, :johnny, nil, true, false]
assert_select 'select option[value="Hello Kitty"]'
assert_select 'select option[value="2"]'
assert_select 'select option[value="4.5"]'
assert_select 'select option[value="johnny"]'
assert_select 'select option[value=""]'
assert_select 'select option[value="true"]'
assert_select 'select option[value="false"]'
end
test 'input includes a blank option even if :include_blank is set to false if the collection includes a nil value' do
with_input_for @user, :age, :select, collection: [nil], include_blank: false
assert_select 'select option[value=""]'
end
test 'input automatically sets include blank' do
with_input_for @user, :age, :select, collection: 18..30
assert_select 'select option[value=""]', ''
end
test 'input translates include blank when set to :translate' do
store_translations(:en, simple_form: { include_blanks: { user: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, include_blank: :translate
assert_select 'select option[value=""]', 'Rather not say'
end
end
test 'input translates include blank with a default' do
store_translations(:en, simple_form: { include_blanks: { defaults: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, include_blank: :translate
assert_select 'select option[value=""]', 'Rather not say'
end
end
test 'input does not translate include blank when set to a string' do
store_translations(:en, simple_form: { include_blanks: { user: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, include_blank: 'Young at heart'
assert_select 'select option[value=""]', 'Young at heart'
end
end
test 'input does not translate include blank when automatically set' do
store_translations(:en, simple_form: { include_blanks: { user: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30
assert_select 'select option[value=""]', ''
end
end
test 'input does not translate include blank when set to true' do
store_translations(:en, simple_form: { include_blanks: { user: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, include_blank: true
assert_select 'select option[value=""]', ''
end
end
test 'input does not translate include blank when set to false' do
store_translations(:en, simple_form: { include_blanks: { user: {
age: 'Rather not say'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, include_blank: false
assert_no_select 'select option[value=""]'
end
end
test 'input does not set include blank if otherwise is told' do
with_input_for @user, :age, :select, collection: 18..30, include_blank: false
assert_no_select 'select option[value=""]'
end
test 'input does not set include blank if prompt is given' do
with_input_for @user, :age, :select, collection: 18..30, prompt: "Please select foo"
assert_no_select 'select option[value=""]', ''
end
test 'input does not set include blank if multiple is given' do
with_input_for @user, :age, :select, collection: 18..30, input_html: { multiple: true }
assert_no_select 'select option[value=""]', ''
end
test 'input translates prompt when set to :translate' do
store_translations(:en, simple_form: { prompts: { user: {
age: 'Select age:'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, prompt: :translate
assert_select 'select option[value=""]', 'Select age:'
end
end
test 'input translates prompt with a default' do
store_translations(:en, simple_form: { prompts: { defaults: {
age: 'Select age:'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, prompt: :translate
assert_select 'select option[value=""]', 'Select age:'
end
end
test 'input does not translate prompt when set to a string' do
store_translations(:en, simple_form: { prompts: { user: {
age: 'Select age:'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, prompt: 'Do it:'
assert_select 'select option[value=""]', 'Do it:'
end
end
test 'input does not translate prompt when set to false' do
store_translations(:en, simple_form: { prompts: { user: {
age: 'Select age:'
} } }) do
with_input_for @user, :age, :select, collection: 18..30, prompt: false
assert_no_select 'select option[value=""]'
end
end
test 'input uses Rails prompt translation as a fallback' do
store_translations(:en, helpers: { select: {
prompt: 'Select value:'
} }) do
with_input_for @user, :age, :select, collection: 18..30, prompt: :translate
assert_select 'select option[value=""]', "Select value:"
end
end
test 'input detects label and value on collections' do
users = [User.build(id: 1, name: "Jose"), User.build(id: 2, name: "Carlos")]
with_input_for @user, :description, :select, collection: users
assert_select 'select option[value="1"]', 'Jose'
assert_select 'select option[value="2"]', 'Carlos'
end
test 'input disables the entire select and no specific options when given `true`' do
with_input_for @user, :description, :select, collection: %w[Jose Carlos], disabled: true
assert_no_select 'select option[value=Jose][disabled=disabled]', 'Jose'
assert_no_select 'select option[value=Carlos][disabled=disabled]', 'Carlos'
assert_select 'select[disabled=disabled]'
assert_select 'div.disabled'
end
test 'input allows disabling only a single given option' do
with_input_for @user, :description, :select, collection: %w[Jose Carlos], disabled: 'Jose'
assert_select 'select option[value=Jose][disabled=disabled]', 'Jose'
assert_no_select 'select option[value=Carlos][disabled=disabled]', 'Carlos'
assert_no_select 'select[disabled=disabled]'
assert_no_select 'div.disabled'
end
test 'input allows disabling multiple given options' do
with_input_for @user, :description, :select, collection: %w[Jose Carlos], disabled: %w[Jose Carlos]
assert_select 'select option[value=Jose][disabled=disabled]', 'Jose'
assert_select 'select option[value=Carlos][disabled=disabled]', 'Carlos'
assert_no_select 'select[disabled=disabled]'
assert_no_select 'div.disabled'
end
test 'input allows overriding label and value method using a lambda for collection selects' do
with_input_for @user, :name, :select,
collection: %w[Jose Carlos],
label_method: ->(i) { i.upcase },
value_method: ->(i) { i.downcase }
assert_select 'select option[value=jose]', "JOSE"
assert_select 'select option[value=carlos]', "CARLOS"
end
test 'input allows overriding only label but not value method using a lambda for collection select' do
with_input_for @user, :name, :select,
collection: %w[Jose Carlos],
label_method: ->(i) { i.upcase }
assert_select 'select option[value=Jose]', "JOSE"
assert_select 'select option[value=Carlos]', "CARLOS"
end
test 'input allows overriding only value but not label method using a lambda for collection select' do
with_input_for @user, :name, :select,
collection: %w[Jose Carlos],
value_method: ->(i) { i.downcase }
assert_select 'select option[value=jose]', "Jose"
assert_select 'select option[value=carlos]', "Carlos"
end
test 'input allows symbols for collections' do
with_input_for @user, :name, :select, collection: %i[jose carlos]
assert_select 'select.select#user_name'
assert_select 'select option[value=jose]', 'jose'
assert_select 'select option[value=carlos]', 'carlos'
end
test 'collection input with select type generates required html attribute only with blank option' do
with_input_for @user, :name, :select, include_blank: true, collection: %w[Jose Carlos]
assert_select 'select.required'
assert_select 'select[required]'
end
test 'collection input with select type generates required html attribute only with blank option or prompt' do
with_input_for @user, :name, :select, prompt: 'Name...', collection: %w[Jose Carlos]
assert_select 'select.required'
assert_select 'select[required]'
end
test "collection input generated aria-label should contain 'true'" do
with_input_for @user, :age, :select, collection: 18..30, prompt: "Please select foo"
assert_select 'select.required'
end
test 'collection input with select type does not generate required html attribute without blank option' do
with_input_for @user, :name, :select, include_blank: false, collection: %w[Jose Carlos]
assert_select 'select.required'
assert_no_select 'select[required]'
end
test 'collection input with select type with multiple attribute generates required html attribute without blank option' do
with_input_for @user, :name, :select, include_blank: false, input_html: { multiple: true }, collection: %w[Jose Carlos]
assert_select 'select.required'
assert_select 'select[required]'
end
test 'collection input with select type with multiple attribute generates required html attribute with blank option' do
with_input_for @user, :name, :select, include_blank: true, input_html: { multiple: true }, collection: %w[Jose Carlos]
assert_select 'select.required'
assert_select 'select[required]'
end
test 'input allows disabled options with a lambda for collection select' do
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
disabled: ->(x) { x == "Carlos" }
assert_select 'select option[value=Carlos][disabled=disabled]', 'Carlos'
assert_select 'select option[value=Antonio]', 'Antonio'
assert_no_select 'select option[value=Antonio][disabled]'
end
test 'input allows disabled and label method with lambdas for collection select' do
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
disabled: ->(x) { x == "Carlos" }, label_method: ->(x) { x.upcase }
assert_select 'select option[value=Carlos][disabled=disabled]', 'CARLOS'
assert_select 'select option[value=Antonio]', 'ANTONIO'
assert_no_select 'select option[value=Antonio][disabled]'
end
test 'input allows a non lambda disabled option with lambda label method for collections' do
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
disabled: "Carlos", label_method: ->(x) { x.upcase }
assert_select 'select option[value=Carlos][disabled=disabled]', 'CARLOS'
assert_select 'select option[value=Antonio]', 'ANTONIO'
assert_no_select 'select option[value=Antonio][disabled]'
end
test 'input allows selected and label method with lambdas for collection select' do
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
selected: ->(x) { x == "Carlos" }, label_method: ->(x) { x.upcase }
assert_select 'select option[value=Carlos][selected=selected]', 'CARLOS'
assert_select 'select option[value=Antonio]', 'ANTONIO'
assert_no_select 'select option[value=Antonio][selected]'
end
test 'input allows a non lambda selected option with lambda label method for collection select' do
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
selected: "Carlos", label_method: ->(x) { x.upcase }
assert_select 'select option[value=Carlos][selected=selected]', 'CARLOS'
assert_select 'select option[value=Antonio]', 'ANTONIO'
assert_no_select 'select option[value=Antonio][selected]'
end
test 'input does not override default selection through attribute value with label method as lambda for collection select' do
@user.name = "Carlos"
with_input_for @user, :name, :select, collection: %w[Carlos Antonio],
label_method: ->(x) { x.upcase }
assert_select 'select option[value=Carlos][selected=selected]', 'CARLOS'
assert_select 'select option[value=Antonio]', 'ANTONIO'
assert_no_select 'select option[value=Antonio][selected]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/color_input_test.rb | test/inputs/color_input_test.rb | # frozen_string_literal: true
require 'test_helper'
class ColorInputTest < ActionView::TestCase
test 'input generates a color field' do
with_input_for @user, :favorite_color, :color
assert_select 'input[type=color].color#user_favorite_color'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/time_zone_input_test.rb | test/inputs/time_zone_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class TimeZoneInputTest < ActionView::TestCase
test 'input generates a time zone select field' do
with_input_for @user, :time_zone, :time_zone
assert_select 'select#user_time_zone'
assert_select 'select option[value=Brasilia]', '(GMT-03:00) Brasilia'
assert_no_select 'select option[value=""][disabled=disabled]'
end
test 'input generates a time zone select field with default' do
with_input_for @user, :time_zone, :time_zone, default: 'Brasilia'
assert_select 'select option[value=Brasilia][selected=selected]'
assert_no_select 'select option[value=""]'
end
test 'input generates a time zone select using options priority' do
with_input_for @user, :time_zone, :time_zone, priority: /Brasilia/
assert_select 'select option[value=""][disabled=disabled]'
assert_no_select 'select option[value=""]', /^$/
end
test 'input does generate select element with required html attribute' do
with_input_for @user, :time_zone, :time_zone
assert_select 'select.required'
assert_select 'select[required]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/collection_check_boxes_input_test.rb | test/inputs/collection_check_boxes_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class CollectionCheckBoxesInputTest < ActionView::TestCase
test 'input check boxes does not include for attribute by default' do
with_input_for @user, :gender, :check_boxes, collection: %i[male female]
assert_select 'label'
assert_no_select 'label[for=user_gender]'
end
test 'input check boxes includes for attribute when giving as html option' do
with_input_for @user, :gender, :check_boxes, collection: %i[male female], label_html: { for: 'gender' }
assert_select 'label[for=gender]'
end
test 'collection input with check_boxes type does not generate required html attribute' do
with_input_for @user, :name, :check_boxes, collection: %w[Jose Carlos]
assert_select 'input.required'
assert_no_select 'input[required]'
end
test 'input does automatic collection translation for check_box types using defaults key' do
store_translations(:en, simple_form: { options: { defaults: {
gender: { male: 'Male', female: 'Female' }
} } } ) do
with_input_for @user, :gender, :check_boxes, collection: %i[male female]
assert_select 'input[type=checkbox][value=male]'
assert_select 'input[type=checkbox][value=female]'
assert_select 'label.collection_check_boxes', 'Male'
assert_select 'label.collection_check_boxes', 'Female'
end
end
test 'input does automatic collection translation for check_box types using specific object key' do
store_translations(:en, simple_form: { options: { user: {
gender: { male: 'Male', female: 'Female' }
} } } ) do
with_input_for @user, :gender, :check_boxes, collection: %i[male female]
assert_select 'input[type=checkbox][value=male]'
assert_select 'input[type=checkbox][value=female]'
assert_select 'label.collection_check_boxes', 'Male'
assert_select 'label.collection_check_boxes', 'Female'
end
end
test 'input that uses automatic collection translation for check_boxes properly sets checked values' do
store_translations(:en, simple_form: { options: { defaults: {
gender: { male: 'Male', female: 'Female' }
} } } ) do
@user.gender = 'male'
with_input_for @user, :gender, :check_boxes, collection: %i[male female]
assert_select 'input[type=checkbox][value=male][checked=checked]'
assert_select 'input[type=checkbox][value=female]'
assert_select 'label.collection_check_boxes', 'Male'
assert_select 'label.collection_check_boxes', 'Female'
end
end
test 'input check boxes does not wrap the collection by default' do
with_input_for @user, :active, :check_boxes
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
test 'input check boxes accepts html options as the last element of collection' do
with_input_for @user, :name, :check_boxes, collection: [['Jose', 'jose', class: 'foo']]
assert_select 'input.foo[type=checkbox][value=jose]'
end
test 'input check boxes wraps the collection in the configured collection wrapper tag' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :check_boxes
assert_select 'form ul input[type=checkbox]', count: 2
end
end
test 'input check boxes does not wrap the collection when configured with falsy values' do
swap SimpleForm, collection_wrapper_tag: false do
with_input_for @user, :active, :check_boxes
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
end
test 'input check boxes allows overriding the collection wrapper tag at input level' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :check_boxes, collection_wrapper_tag: :section
assert_select 'form section input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
end
test 'input check boxes allows disabling the collection wrapper tag at input level' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :check_boxes, collection_wrapper_tag: false
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form ul'
end
end
test 'input check boxes renders the wrapper tag with the configured wrapper class' do
swap SimpleForm, collection_wrapper_tag: :ul, collection_wrapper_class: 'inputs-list' do
with_input_for @user, :active, :check_boxes
assert_select 'form ul.inputs-list input[type=checkbox]', count: 2
end
end
test 'input check boxes allows giving wrapper class at input level only' do
swap SimpleForm, collection_wrapper_tag: :ul do
with_input_for @user, :active, :check_boxes, collection_wrapper_class: 'items-list'
assert_select 'form ul.items-list input[type=checkbox]', count: 2
end
end
test 'input check boxes uses both configured and given wrapper classes for wrapper tag' do
swap SimpleForm, collection_wrapper_tag: :ul, collection_wrapper_class: 'inputs-list' do
with_input_for @user, :active, :check_boxes, collection_wrapper_class: 'items-list'
assert_select 'form ul.inputs-list.items-list input[type=checkbox]', count: 2
end
end
test 'input check boxes wraps each item in the configured item wrapper tag' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :check_boxes
assert_select 'form li input[type=checkbox]', count: 2
end
end
test 'input check boxes does not wrap items when configured with falsy values' do
swap SimpleForm, item_wrapper_tag: false do
with_input_for @user, :active, :check_boxes
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form li'
end
end
test 'input check boxes allows overriding the item wrapper tag at input level' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :check_boxes, item_wrapper_tag: :dl
assert_select 'form dl input[type=checkbox]', count: 2
assert_no_select 'form li'
end
end
test 'input check boxes allows disabling the item wrapper tag at input level' do
swap SimpleForm, item_wrapper_tag: :ul do
with_input_for @user, :active, :check_boxes, item_wrapper_tag: false
assert_select 'form input[type=checkbox]', count: 2
assert_no_select 'form li'
end
end
test 'input check boxes wraps items in a span tag by default' do
with_input_for @user, :active, :check_boxes
assert_select 'form span input[type=checkbox]', count: 2
end
test 'input check boxes renders the item wrapper tag with a default class "checkbox"' do
with_input_for @user, :active, :check_boxes, item_wrapper_tag: :li
assert_select 'form li.checkbox input[type=checkbox]', count: 2
end
test 'input check boxes renders the item wrapper tag with the configured item wrapper class' do
swap SimpleForm, item_wrapper_tag: :li, item_wrapper_class: 'item' do
with_input_for @user, :active, :check_boxes
assert_select 'form li.checkbox.item input[type=checkbox]', count: 2
end
end
test 'input check boxes allows giving item wrapper class at input level only' do
swap SimpleForm, item_wrapper_tag: :li do
with_input_for @user, :active, :check_boxes, item_wrapper_class: 'item'
assert_select 'form li.checkbox.item input[type=checkbox]', count: 2
end
end
test 'input check boxes uses both configured and given item wrapper classes for item wrapper tag' do
swap SimpleForm, item_wrapper_tag: :li, item_wrapper_class: 'item' do
with_input_for @user, :active, :check_boxes, item_wrapper_class: 'inline'
assert_select 'form li.checkbox.item.inline input[type=checkbox]', count: 2
end
end
test 'input check boxes respects the nested boolean style config, generating nested label > input' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :check_boxes
assert_select 'span.checkbox > label > input#user_active_true[type=checkbox]'
assert_select 'span.checkbox > label', 'Yes'
assert_select 'span.checkbox > label > input#user_active_false[type=checkbox]'
assert_select 'span.checkbox > label', 'No'
assert_no_select 'label.collection_radio_buttons'
end
end
test 'input check boxes with nested style does not overrides configured item wrapper tag' do
swap SimpleForm, boolean_style: :nested, item_wrapper_tag: :li do
with_input_for @user, :active, :check_boxes
assert_select 'li.checkbox > label > input'
end
end
test 'input check boxes with nested style does not overrides given item wrapper tag' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :check_boxes, item_wrapper_tag: :li
assert_select 'li.checkbox > label > input'
end
end
test 'input check boxes with nested style accepts giving extra wrapper classes' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :check_boxes, item_wrapper_class: "inline"
assert_select 'span.checkbox.inline > label > input'
end
end
test 'input check boxes with nested style renders item labels with specified class' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :active, :check_boxes, item_label_class: "test"
assert_select 'span.checkbox > label.test > input'
end
end
test 'input check boxes with nested style and falsey input wrapper renders item labels with specified class' do
swap SimpleForm, boolean_style: :nested, item_wrapper_tag: false do
with_input_for @user, :active, :check_boxes, item_label_class: "checkbox-inline"
assert_select 'label.checkbox-inline > input'
assert_no_select 'span.checkbox'
end
end
test 'input check boxes wrapper class are not included when set to falsey' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_input_for @user, :gender, :check_boxes, collection: %i[male female]
assert_no_select 'label.checkbox'
end
end
test 'input check boxes custom wrapper class is included when include input wrapper class is falsey' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_input_for @user, :gender, :check_boxes, collection: %i[male female], item_wrapper_class: 'custom'
assert_no_select 'label.checkbox'
assert_select 'span.custom'
end
end
test 'input check boxes with nested style and namespace uses the right for attribute' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_concat_form_for @user, namespace: :foo do |f|
concat f.input :gender, as: :check_boxes, collection: %i[male female]
end
assert_select 'label[for=foo_user_gender_male]'
assert_select 'label[for=foo_user_gender_female]'
end
end
test 'input check boxes with nested style and index uses the right for attribute' do
swap SimpleForm, include_default_input_wrapper_class: false, boolean_style: :nested do
with_concat_form_for @user, index: 1 do |f|
concat f.input :gender, as: :check_boxes, collection: %i[male female]
end
assert_select 'label[for=user_1_gender_male]'
assert_select 'label[for=user_1_gender_female]'
end
end
test 'input check boxes with nested style accepts non-string attribute as label' do
swap SimpleForm, boolean_style: :nested do
with_input_for @user, :amount,
:check_boxes,
collection: { 100 => 'hundred', 200 => 'two_hundred' },
label_method: :first,
value_method: :second
assert_select 'input[type=checkbox][value=hundred]'
assert_select 'input[type=checkbox][value=two_hundred]'
assert_select 'span.checkbox > label', '100'
assert_select 'span.checkbox > label', '200'
end
end
test 'input check boxes with inline style support label custom classes' do
swap SimpleForm, boolean_style: :inline do
with_input_for @user, :gender, :check_boxes, collection: %i[male female], item_label_class: 'beautiful-label'
assert_select 'label.beautiful-label', count: 2
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/numeric_input_test.rb | test/inputs/numeric_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class NumericInputTest < ActionView::TestCase
test 'input generates an integer text field for integer attributes ' do
with_input_for @user, :age, :integer
assert_select 'input[type=number].integer#user_age'
end
test 'input generates a float text field for float attributes ' do
with_input_for @user, :age, :float
assert_select 'input[type=number].float#user_age'
end
test 'input generates a decimal text field for decimal attributes ' do
with_input_for @user, :age, :decimal
assert_select 'input[type=number].decimal#user_age'
end
test 'input does not generate min attribute by default' do
with_input_for @user, :age, :integer
assert_no_select 'input[min]'
end
test 'input does not generate max attribute by default' do
with_input_for @user, :age, :integer
assert_no_select 'input[max]'
end
test 'input infers min value from integer attributes with greater than validation' do
with_input_for @other_validating_user, :age, :float
assert_no_select 'input[min]'
with_input_for @other_validating_user, :age, :integer
assert_select 'input[min="18"]'
end
test 'input infers min value from integer attributes with greater than validation using symbol' do
with_input_for @validating_user, :amount, :float
assert_no_select 'input[min]'
with_input_for @validating_user, :amount, :integer
assert_select 'input[min="11"]'
end
test 'input infers min value from integer attributes with greater than or equal to validation using symbol' do
with_input_for @validating_user, :attempts, :float
assert_select 'input[min="1"]'
with_input_for @validating_user, :attempts, :integer
assert_select 'input[min="1"]'
end
test 'input infers min value from integer attributes with greater than validation using proc' do
with_input_for @other_validating_user, :amount, :float
assert_no_select 'input[min]'
with_input_for @other_validating_user, :amount, :integer
assert_select 'input[min="20"]'
end
test 'input infers min value from integer attributes with greater than or equal to validation using proc' do
with_input_for @other_validating_user, :attempts, :float
assert_select 'input[min="19"]'
with_input_for @other_validating_user, :attempts, :integer
assert_select 'input[min="19"]'
end
test 'input infers max value from attributes with less than validation' do
with_input_for @other_validating_user, :age, :float
assert_no_select 'input[max]'
with_input_for @other_validating_user, :age, :integer
assert_select 'input[max="99"]'
end
test 'input infers max value from attributes with less than validation using symbol' do
with_input_for @validating_user, :amount, :float
assert_no_select 'input[max]'
with_input_for @validating_user, :amount, :integer
assert_select 'input[max="99"]'
end
test 'input infers max value from attributes with less than or equal to validation using symbol' do
with_input_for @validating_user, :attempts, :float
assert_select 'input[max="100"]'
with_input_for @validating_user, :attempts, :integer
assert_select 'input[max="100"]'
end
test 'input infers max value from attributes with less than validation using proc' do
with_input_for @other_validating_user, :amount, :float
assert_no_select 'input[max]'
with_input_for @other_validating_user, :amount, :integer
assert_select 'input[max="118"]'
end
test 'input infers max value from attributes with less than or equal to validation using proc' do
with_input_for @other_validating_user, :attempts, :float
assert_select 'input[max="119"]'
with_input_for @other_validating_user, :attempts, :integer
assert_select 'input[max="119"]'
end
test 'input has step value of any except for integer attribute' do
with_input_for @validating_user, :age, :float
assert_select 'input[step="any"]'
with_input_for @validating_user, :age, :integer
assert_select 'input[step="1"]'
with_input_for @validating_user, :age, :integer, as: :decimal, input_html: { step: 0.5 }
assert_select 'input[step="0.5"]'
end
test 'numeric input does not generate placeholder by default' do
with_input_for @user, :age, :integer
assert_no_select 'input[placeholder]'
end
test 'numeric input accepts the placeholder option' do
with_input_for @user, :age, :integer, placeholder: 'Put in your age'
assert_select 'input.integer[placeholder="Put in your age"]'
end
test 'numeric input uses i18n to translate placeholder text' do
store_translations(:en, simple_form: { placeholders: { user: {
age: 'Age goes here'
} } }) do
with_input_for @user, :age, :integer
assert_select 'input.integer[placeholder="Age goes here"]'
end
end
# Numeric input but HTML5 disabled
test 'when not using HTML5 input does not generate field with type number and use text instead' do
swap_wrapper do
with_input_for @user, :age, :integer
assert_no_select "input[type=number]"
assert_no_select "input#user_age[text]"
end
end
test 'when not using HTML5 input does not use min or max or step attributes' do
swap_wrapper do
with_input_for @validating_user, :age, :integer
assert_no_select "input[type=number]"
assert_no_select "input[min]"
assert_no_select "input[max]"
assert_no_select "input[step]"
end
end
%i[integer float decimal].each do |type|
test "#{type} input infers min value from attributes with greater than or equal validation" do
with_input_for @validating_user, :age, type
assert_select 'input[min="18"]'
end
test "#{type} input infers the max value from attributes with less than or equal to validation" do
with_input_for @validating_user, :age, type
assert_select 'input[max="99"]'
end
end
test 'min_max does not emit max value as bare string' do
with_input_for @other_validating_user, :age, :integer
assert_select 'input[max]'
assert_no_select 'div', %r{^99}
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/country_input_test.rb | test/inputs/country_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class CountryInputTest < ActionView::TestCase
COUNTRY_SELECT_SEPARATOR =
if Gem::Version.new(CountrySelect::VERSION) >= Gem::Version.new("11.0.0")
"hr"
else
'option[value="---------------"][disabled=disabled]'
end
test 'input generates a country select field' do
with_input_for @user, :country, :country
assert_select 'select#user_country'
assert_select 'select option[value=BR]', 'Brazil'
assert_no_select 'select option[value=""][disabled=disabled]'
assert_no_select "select #{COUNTRY_SELECT_SEPARATOR}"
end
test 'input generates a country select with SimpleForm default' do
swap SimpleForm, country_priority: [ 'Brazil' ] do
with_input_for @user, :country, :country
assert_select %(select option[value="BR"] + #{COUNTRY_SELECT_SEPARATOR})
end
end
test 'input generates a country select using options priority' do
with_input_for @user, :country, :country, priority: [ 'Ukraine' ]
assert_select %(select option[value="UA"] + #{COUNTRY_SELECT_SEPARATOR})
end
test 'input does generate select element with required html attribute' do
with_input_for @user, :country, :country
assert_select 'select.required'
assert_select 'select[required]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/hidden_input_test.rb | test/inputs/hidden_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class HiddenInputTest < ActionView::TestCase
test 'input generates a hidden field' do
with_input_for @user, :name, :hidden
assert_no_select 'input[type=text]'
assert_select 'input#user_name[type=hidden]'
end
test 'hint does not be generated for hidden fields' do
store_translations(:en, simple_form: { hints: { user: { name: "text" } } }) do
with_input_for @user, :name, :hidden
assert_no_select 'span.hint'
end
end
test 'label does not be generated for hidden inputs' do
with_input_for @user, :name, :hidden
assert_no_select 'label'
end
test 'required/optional options does not be generated for hidden inputs' do
with_input_for @user, :name, :hidden
assert_no_select 'input.required'
assert_no_select 'input[required]'
assert_no_select 'input.optional'
assert_select 'input.hidden#user_name'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/disabled_test.rb | test/inputs/disabled_test.rb | # frozen_string_literal: true
require 'test_helper'
class DisabledTest < ActionView::TestCase
test 'string input is disabled when disabled option is true' do
with_input_for @user, :name, :string, disabled: true
assert_select 'input.string.disabled[disabled]'
end
test 'text input is disabled when disabled option is true' do
with_input_for @user, :description, :text, disabled: true
assert_select 'textarea.text.disabled[disabled]'
end
test 'numeric input is disabled when disabled option is true' do
with_input_for @user, :age, :integer, disabled: true
assert_select 'input.integer.disabled[disabled]'
end
test 'date input is disabled when disabled option is true' do
with_input_for @user, :born_at, :date, disabled: true
assert_select 'select.date.disabled[disabled]'
end
test 'datetime input is disabled when disabled option is true' do
with_input_for @user, :created_at, :datetime, disabled: true
assert_select 'select.datetime.disabled[disabled]'
end
test 'string input does not be disabled when disabled option is false' do
with_input_for @user, :name, :string, disabled: false
assert_no_select 'input.string.disabled[disabled]'
end
test 'text input does not be disabled when disabled option is false' do
with_input_for @user, :description, :text, disabled: false
assert_no_select 'textarea.text.disabled[disabled]'
end
test 'numeric input does not be disabled when disabled option is false' do
with_input_for @user, :age, :integer, disabled: false
assert_no_select 'input.integer.disabled[disabled]'
end
test 'date input does not be disabled when disabled option is false' do
with_input_for @user, :born_at, :date, disabled: false
assert_no_select 'select.date.disabled[disabled]'
end
test 'datetime input does not be disabled when disabled option is false' do
with_input_for @user, :created_at, :datetime, disabled: false
assert_no_select 'select.datetime.disabled[disabled]'
end
test 'string input does not be disabled when disabled option is not present' do
with_input_for @user, :name, :string
assert_no_select 'input.string.disabled[disabled]'
end
test 'text input does not be disabled when disabled option is not present' do
with_input_for @user, :description, :text
assert_no_select 'textarea.text.disabled[disabled]'
end
test 'numeric input does not be disabled when disabled option is not present' do
with_input_for @user, :age, :integer
assert_no_select 'input.integer.disabled[disabled]'
end
test 'date input does not be disabled when disabled option is not present' do
with_input_for @user, :born_at, :date
assert_no_select 'select.date.disabled[disabled]'
end
test 'datetime input does not be disabled when disabled option is not present' do
with_input_for @user, :created_at, :datetime
assert_no_select 'select.datetime.disabled[disabled]'
end
test 'input_field collection allows disabled select' do
with_input_field_for @user, :description, collection: ['foo', 'bar'], disabled: true
assert_select 'select[disabled]'
assert_no_select 'option[disabled]'
end
test 'input_field collection allows individual disabled options' do
with_input_field_for @user, :description, collection: ['foo', 'bar'], disabled: 'bar'
assert_no_select 'select[disabled]'
assert_no_select 'option[disabled][value=foo]'
assert_select 'option[disabled][value=bar]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/weekday_input_test.rb | test/inputs/weekday_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class WeekdayInputTest < ActionView::TestCase
test 'input generates a weekday select' do
with_input_for @user, :born_at, :weekday
assert_select 'select.weekday#user_born_at'
end
test 'input generates a weekday select that accepts placeholder' do
with_input_for @user, :born_at, :weekday, placeholder: 'Put in a weekday'
assert_select 'select.weekday[placeholder="Put in a weekday"]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/rich_text_area_input_test.rb | test/inputs/rich_text_area_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class RichTextAreaInputTest < ActionView::TestCase
test 'input generates a text area for text attributes' do
with_input_for @user, :description, :text
assert_select 'textarea.text#user_description'
end
test 'input generates a text area for text attributes that accept placeholder' do
with_input_for @user, :description, :text, placeholder: 'Put in some text'
assert_select 'textarea.text[placeholder="Put in some text"]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/discovery_test.rb | test/inputs/discovery_test.rb | # frozen_string_literal: true
require 'test_helper'
class DiscoveryTest < ActionView::TestCase
# Setup new inputs and remove them after the test.
def discovery(value = false)
swap SimpleForm, cache_discovery: value do
begin
load "support/discovery_inputs.rb"
yield
ensure
SimpleForm::FormBuilder.discovery_cache.clear
Object.send :remove_const, :StringInput
Object.send :remove_const, :NumericInput
Object.send :remove_const, :CustomizedInput
Object.send :remove_const, :DeprecatedInput
Object.send :remove_const, :CollectionSelectInput
Object.send :remove_const, :FileInput
CustomInputs.send :remove_const, :CustomizedInput
CustomInputs.send :remove_const, :PasswordInput
CustomInputs.send :remove_const, :NumericInput
end
end
end
test 'builder does not discover new inputs if cached' do
with_form_for @user, :name
assert_select 'form input#user_name.string'
discovery(true) do
with_form_for @user, :name
assert_no_select 'form section input#user_name.string'
end
end
test 'builder discovers new inputs' do
discovery do
with_form_for @user, :name, as: :customized
assert_select 'form section input#user_name.string'
end
end
test 'builder does not discover new inputs if discovery is off' do
with_form_for @user, :name
assert_select 'form input#user_name.string'
swap SimpleForm, inputs_discovery: false do
discovery do
with_form_for @user, :name
assert_no_select 'form section input#user_name.string'
end
end
end
test 'builder discovers new inputs from mappings if not cached' do
discovery do
with_form_for @user, :name
assert_select 'form section input#user_name.string'
end
end
test 'builder discovers new inputs from internal fallbacks if not cached' do
discovery do
with_form_for @user, :age
assert_select 'form section input#user_age.numeric.integer'
end
end
test 'builder discovers new mapped inputs from configured namespaces if not cached' do
discovery do
swap SimpleForm, custom_inputs_namespaces: ['CustomInputs'] do
with_form_for @user, :password
assert_select 'form input#user_password.password-custom-input'
end
end
end
test 'builder discovers new mapped inputs from configured namespaces before the ones from top level namespace' do
discovery do
swap SimpleForm, custom_inputs_namespaces: ['CustomInputs'] do
with_form_for @user, :age
assert_select 'form input#user_age.numeric-custom-input'
end
end
end
test 'builder discovers new custom inputs from configured namespace before the ones from top level namespace' do
discovery do
swap SimpleForm, custom_inputs_namespaces: ['CustomInputs'] do
with_form_for @user, :name, as: 'customized'
assert_select 'form input#user_name.customized-namespace-custom-input'
end
end
end
test 'raises error when configured namespace does not exists' do
discovery do
swap SimpleForm, custom_inputs_namespaces: ['InvalidNamespace'] do
assert_raise NameError do
with_form_for @user, :age
end
end
end
end
test 'new inputs can override the input_html_options' do
discovery do
with_form_for @user, :active, as: :select
assert_select 'form select#user_active.select.chosen'
end
end
test 'does not duplicate the html classes giving a extra class' do
discovery do
swap SimpleForm, input_class: 'custom-default-input-class' do
with_form_for @user, :active, as: :select
assert_select 'form select#user_active.select' do
# Make sure class list contains 'chosen' only once.
assert_select ":match('class', ?)", /^(?!.*\bchosen\b.*\bchosen\b).*\bchosen\b.*$/
end
end
end
end
test 'new inputs can override the default input_html_classes' do
discovery do
with_form_for @user, :avatar, as: :file
assert_no_select 'form input[type=file]#user_avatar.file.file-upload'
assert_select 'form input[type=file]#user_avatar.file-upload'
end
end
test 'inputs method without wrapper_options are deprecated' do
discovery do
assert_deprecated('input method now accepts a `wrapper_options` argument.', SimpleForm.deprecator) do
with_form_for @user, :name, as: :deprecated
end
assert_select 'form section input#user_name.string'
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/test/inputs/text_input_test.rb | test/inputs/text_input_test.rb | # frozen_string_literal: true
# encoding: UTF-8
require 'test_helper'
class TextInputTest < ActionView::TestCase
test 'input generates a text area for text attributes' do
with_input_for @user, :description, :text
assert_select 'textarea.text#user_description'
end
test 'input generates a text area for text attributes that accept placeholder' do
with_input_for @user, :description, :text, placeholder: 'Put in some text'
assert_select 'textarea.text[placeholder="Put in some text"]'
end
test 'input generates a placeholder from the translations' do
store_translations(:en, simple_form: { placeholders: { user: { name: "placeholder from i18n en.simple_form.placeholders.user.name" } } }) do
with_input_for @user, :name, :text
assert_select 'textarea.text[placeholder="placeholder from i18n en.simple_form.placeholders.user.name"]'
end
end
test 'input gets maxlength from column definition for text attributes' do
with_input_for @user, :description, :text
assert_select 'textarea.text[maxlength="200"]'
end
test 'input infers maxlength column definition from validation when present for text attributes' do
with_input_for @validating_user, :description, :text
assert_select 'textarea.text[maxlength="50"]'
end
test 'input infers minlength column definition from validation when present for text attributes' do
with_input_for @validating_user, :description, :text
assert_select 'textarea.text[minlength="15"]'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form.rb | lib/simple_form.rb | # frozen_string_literal: true
require 'action_view'
require 'action_pack'
require 'simple_form/action_view_extensions/form_helper'
require 'simple_form/action_view_extensions/builder'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/reverse_merge'
module SimpleForm
extend ActiveSupport::Autoload
autoload :Helpers
autoload :Wrappers
eager_autoload do
autoload :Components
autoload :ErrorNotification
autoload :FormBuilder
autoload :Inputs
end
def self.eager_load!
super
SimpleForm::Inputs.eager_load!
SimpleForm::Components.eager_load!
end
CUSTOM_INPUT_DEPRECATION_WARN = <<-WARN
%{name} method now accepts a `wrapper_options` argument. The method definition without the argument is deprecated and will be removed in the next Simple Form version. Change your code from:
def %{name}
to
def %{name}(wrapper_options)
See https://github.com/heartcombo/simple_form/pull/997 for more information.
WARN
FILE_METHODS_DEPRECATION_WARN = <<-WARN
[SIMPLE_FORM] SimpleForm.file_methods is deprecated and has no effect.
Since version 5, Simple Form now supports automatically discover of file inputs for the following Gems: activestorage, carrierwave, paperclip, refile and shrine.
If you are using a custom method that is not from one of the supported Gems, please change your forms to pass the input type explicitly:
<%= form.input :avatar, as: :file %>
See http://blog.plataformatec.com.br/2019/09/incorrect-access-control-in-simple-form-cve-2019-16676 for more information.
WARN
@@configured = false
def self.configured? #:nodoc:
@@configured
end
def self.deprecator
@deprecator ||= ActiveSupport::Deprecation.new("5.3", "SimpleForm")
end
## CONFIGURATION OPTIONS
# Method used to tidy up errors.
mattr_accessor :error_method
@@error_method = :first
# Default tag used for error notification helper.
mattr_accessor :error_notification_tag
@@error_notification_tag = :p
# CSS class to add for error notification helper.
mattr_accessor :error_notification_class
@@error_notification_class = :error_notification
# Series of attempts to detect a default label method for collection.
mattr_accessor :collection_label_methods
@@collection_label_methods = %i[to_label name title to_s]
# Series of attempts to detect a default value method for collection.
mattr_accessor :collection_value_methods
@@collection_value_methods = %i[id to_s]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
mattr_accessor :collection_wrapper_tag
@@collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers, defaulting to none.
mattr_accessor :collection_wrapper_class
@@collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a :label.
mattr_accessor :item_wrapper_tag
@@item_wrapper_tag = :span
# You can define the class to use on all item wrappers, defaulting to none.
mattr_accessor :item_wrapper_class
@@item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
mattr_accessor :label_text
@@label_text = ->(label, required, explicit_label) { "#{required} #{label}" }
# You can define the class to be used on all labels. Defaults to none.
mattr_accessor :label_class
@@label_class = nil
# Define the way to render check boxes / radio buttons with labels.
# inline: input + label (default)
# nested: label > input
mattr_accessor :boolean_style
@@boolean_style = :inline
# DEPRECATED: You can define the class to be used on all forms. Default is
# simple_form.
mattr_reader :form_class
@@form_class = :simple_form
# You can define the default class to be used on all forms. Can be overridden
# with `html: { :class }`. Defaults to none.
mattr_accessor :default_form_class
@@default_form_class = nil
# You can define which elements should obtain additional classes.
mattr_accessor :generate_additional_classes_for
@@generate_additional_classes_for = %i[wrapper label input]
# Whether attributes are required by default or not.
mattr_accessor :required_by_default
@@required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
mattr_accessor :browser_validations
@@browser_validations = true
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value, such as { /count/ => :integer }.
mattr_accessor :input_mappings
@@input_mappings = nil
# Custom wrappers for input types. This should be a hash containing an input
# type as key and the wrapper that will be used for all inputs with specified type.
# e.g { string: :string_wrapper, boolean: :boolean_wrapper }
# You can also set a wrapper mapping per form basis.
# e.g simple_form_for(@foo, wrapper_mappings: { check_boxes: :bootstrap_checkbox })
mattr_accessor :wrapper_mappings
@@wrapper_mappings = nil
# Namespaces where SimpleForm should look for custom input classes that override
# default inputs. Namespaces are given as string to allow lazy loading inputs.
# e.g. config.custom_inputs_namespaces << "CustomInputs"
# will try to find CustomInputs::NumericInput when an :integer
# field is called.
mattr_accessor :custom_inputs_namespaces
@@custom_inputs_namespaces = []
# Default priority for time_zone inputs.
mattr_accessor :time_zone_priority
@@time_zone_priority = nil
# Default priority for country inputs.
mattr_accessor :country_priority
@@country_priority = nil
# When off, do not use translations in labels. Disabling translation in
# hints and placeholders can be done manually in the wrapper API.
mattr_accessor :translate_labels
@@translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
mattr_accessor :inputs_discovery
@@inputs_discovery = true
# Cache SimpleForm inputs discovery.
mattr_accessor :cache_discovery
@@cache_discovery = defined?(Rails.env) && !Rails.env.development?
# Adds a class to each generated button, mostly for compatibility.
mattr_accessor :button_class
@@button_class = 'button'
# Override the default ActiveModelHelper behaviour of wrapping the input.
# This gets taken care of semantically by adding an error class to the wrapper tag
# containing the input.
mattr_accessor :field_error_proc
@@field_error_proc = proc do |html_tag, instance_tag|
html_tag
end
# Adds a class to each generated inputs
mattr_accessor :input_class
@@input_class = nil
# Defines if an input wrapper class should be included or not
mattr_accessor :include_default_input_wrapper_class
@@include_default_input_wrapper_class = true
# Define the default class of the input wrapper of the boolean input.
mattr_accessor :boolean_label_class
@@boolean_label_class = 'checkbox'
## WRAPPER CONFIGURATION
# The default wrapper to be used by the FormBuilder.
mattr_accessor :default_wrapper
@@default_wrapper = :default
@@wrappers = {} #:nodoc:
mattr_accessor :i18n_scope
@@i18n_scope = 'simple_form'
mattr_accessor :input_field_error_class
@@input_field_error_class = nil
mattr_accessor :input_field_valid_class
@@input_field_valid_class = nil
# Retrieves a given wrapper
def self.wrapper(name)
@@wrappers[name.to_s] or raise WrapperNotFound, "Couldn't find wrapper with name #{name}"
end
# Raised when fails to find a given wrapper name
class WrapperNotFound < StandardError
end
# Define a new wrapper using SimpleForm::Wrappers::Builder
# and store it in the given name.
def self.wrappers(*args, &block)
if block_given?
options = args.extract_options!
name = args.first || :default
@@wrappers[name.to_s] = build(options, &block)
else
@@wrappers
end
end
# Builds a new wrapper using SimpleForm::Wrappers::Builder.
def self.build(options = {})
options[:tag] = :div if options[:tag].nil?
builder = SimpleForm::Wrappers::Builder.new(options)
yield builder
SimpleForm::Wrappers::Root.new(builder.to_a, options)
end
wrappers class: :input, hint_class: :field_with_hint, error_class: :field_with_errors, valid_class: :field_without_errors do |b|
b.use :html5
b.use :min_max
b.use :maxlength
b.use :minlength
b.use :placeholder
b.optional :pattern
b.optional :readonly
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
end
def self.additional_classes_for(component)
generate_additional_classes_for.include?(component) ? yield : []
end
## SETUP
def self.default_input_size=(*)
SimpleForm.deprecator.warn "[SIMPLE_FORM] SimpleForm.default_input_size= is deprecated and has no effect", caller
end
def self.form_class=(value)
SimpleForm.deprecator.warn "[SIMPLE_FORM] SimpleForm.form_class= is deprecated and will be removed in 4.x. Use SimpleForm.default_form_class= instead", caller
@@form_class = value
end
def self.file_methods=(file_methods)
SimpleForm.deprecator.warn(FILE_METHODS_DEPRECATION_WARN, caller)
@@file_methods = file_methods
end
def self.file_methods
SimpleForm.deprecator.warn(FILE_METHODS_DEPRECATION_WARN, caller)
@@file_methods
end
# Default way to setup Simple Form. Run rails generate simple_form:install
# to create a fresh initializer with all configuration values.
def self.setup
@@configured = true
yield self
end
# Includes a component to be used by Simple Form. Methods defined in a
# component will be exposed to be used in the wrapper as Simple::Components
#
# Examples
#
# # The application needs to tell where the components will be.
# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }
#
# # Create a custom component in the path specified above.
# # lib/components/input_group_component.rb
# module InputGroupComponent
# def prepend
# ...
# end
#
# def append
# ...
# end
# end
#
# SimpleForm.setup do |config|
# # Create a wrapper using the custom component.
# config.wrappers :input_group, tag: :div, error_class: :error do |b|
# b.use :label
# b.optional :prepend
# b.use :input
# b.use :append
# end
# end
#
# # Using the custom component in the form.
# <%= simple_form_for @blog, wrapper: input_group do |f| %>
# <%= f.input :title, prepend: true %>
# <% end %>
#
def self.include_component(component)
if Module === component
SimpleForm::Inputs::Base.include(component)
else
raise TypeError, "SimpleForm.include_component expects a module but got: #{component.class}"
end
end
end
require 'simple_form/railtie' if defined?(Rails)
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/error_notification.rb | lib/simple_form/error_notification.rb | # frozen_string_literal: true
module SimpleForm
class ErrorNotification
delegate :object, :object_name, :template, to: :@builder
def initialize(builder, options)
@builder = builder
@message = options.delete(:message)
@options = options
end
def render
if has_errors?
template.content_tag(error_notification_tag, error_message, html_options)
end
end
protected
def errors
object.errors
end
def has_errors?
object && object.respond_to?(:errors) && errors.present?
end
def error_message
(@message || translate_error_notification).html_safe
end
def error_notification_tag
SimpleForm.error_notification_tag
end
def html_options
@options[:class] = "#{SimpleForm.error_notification_class} #{@options[:class]}".strip
@options
end
def translate_error_notification
lookups = []
lookups << :"#{object_name}"
lookups << :default_message
lookups << "Please review the problems below:"
I18n.t(lookups.shift, scope: :"simple_form.error_notification", default: lookups)
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/version.rb | lib/simple_form/version.rb | # frozen_string_literal: true
module SimpleForm
VERSION = "5.4.0".freeze
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/map_type.rb | lib/simple_form/map_type.rb | # frozen_string_literal: true
require 'active_support/core_ext/class/attribute'
module SimpleForm
module MapType
def self.extended(base)
base.class_attribute :mappings
base.mappings = {}
end
def map_type(*types)
map_to = types.extract_options![:to]
raise ArgumentError, "You need to give :to as option to map_type" unless map_to
self.mappings = mappings.merge types.each_with_object({}) { |t, m| m[t] = map_to }
end
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/components.rb | lib/simple_form/components.rb | # frozen_string_literal: true
module SimpleForm
# Components are a special type of helpers that can work on their own.
# For example, by using a component, it will automatically change the
# output under given circumstances without user input. For example,
# the disabled helper always need a disabled: true option given
# to the input in order to be enabled. On the other hand, things like
# hints can generate output automatically by doing I18n lookups.
module Components
extend ActiveSupport::Autoload
autoload :Errors
autoload :Hints
autoload :HTML5
autoload :LabelInput
autoload :Labels
autoload :MinMax
autoload :Maxlength
autoload :Minlength
autoload :Pattern
autoload :Placeholders
autoload :Readonly
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
heartcombo/simple_form | https://github.com/heartcombo/simple_form/blob/584127a00bfe027ff5fb779fa11f859045d5ae9f/lib/simple_form/helpers.rb | lib/simple_form/helpers.rb | # frozen_string_literal: true
module SimpleForm
# Helpers are made of several helpers that cannot be turned on automatically.
# For instance, disabled cannot be turned on automatically, it requires the
# user to explicitly pass the option disabled: true so it may work.
module Helpers
autoload :Autofocus, 'simple_form/helpers/autofocus'
autoload :Disabled, 'simple_form/helpers/disabled'
autoload :Readonly, 'simple_form/helpers/readonly'
autoload :Required, 'simple_form/helpers/required'
autoload :Validators, 'simple_form/helpers/validators'
end
end
| ruby | MIT | 584127a00bfe027ff5fb779fa11f859045d5ae9f | 2026-01-04T15:39:08.979660Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.