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 |
|---|---|---|---|---|---|---|---|---|
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/framework.rb | lib/capistrano/framework.rb | load File.expand_path("../tasks/framework.rake", __FILE__)
require "capistrano/install"
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/proc_helpers.rb | lib/capistrano/proc_helpers.rb | module Capistrano
module ProcHelpers
module_function
# Tests whether the given object appears to respond to `call` with
# zero parameters. In Capistrano, such a proc is used to represent a
# "deferred value". That is, a value that is resolved by invoking `call` at
# the time it is first needed.
def callable_without_parameters?(x)
x.respond_to?(:call) && (!x.respond_to?(:arity) || x.arity.zero?)
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/all.rb | lib/capistrano/all.rb | require "rake"
require "sshkit"
require "io/console"
Rake.application.options.trace = true
require "capistrano/version"
require "capistrano/version_validator"
require "capistrano/i18n"
require "capistrano/dsl"
require "capistrano/application"
require "capistrano/configuration"
require "capistrano/configuration/scm_resolver"
module Capistrano
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dsl/stages.rb | lib/capistrano/dsl/stages.rb | module Capistrano
module DSL
module Stages
RESERVED_NAMES = %w(deploy doctor install).freeze
private_constant :RESERVED_NAMES
def stages
names = Dir[stage_definitions].map { |f| File.basename(f, ".rb") }
assert_valid_stage_names(names)
names
end
def stage_definitions
stage_config_path.join("*.rb")
end
def stage_set?
!!fetch(:stage, false)
end
private
def assert_valid_stage_names(names)
invalid = names.find { |n| RESERVED_NAMES.include?(n) }
return if invalid.nil?
raise t("error.invalid_stage_name", name: invalid, path: stage_config_path.join("#{invalid}.rb"))
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dsl/env.rb | lib/capistrano/dsl/env.rb | require "forwardable"
module Capistrano
module DSL
module Env
extend Forwardable
def_delegators :env,
:configure_backend, :fetch, :set, :set_if_empty, :delete,
:ask, :role, :server, :primary, :validate, :append,
:remove, :dry_run?, :install_plugin, :any?, :is_question?,
:configure_scm, :scm_plugin_installed?
def roles(*names)
env.roles_for(names.flatten)
end
def role_properties(*names, &block)
env.role_properties_for(names, &block)
end
def release_roles(*names)
if names.last.is_a? Hash
names.last[:exclude] = :no_release
else
names << { exclude: :no_release }
end
roles(*names)
end
def env
Configuration.env
end
def release_timestamp
env.timestamp.strftime("%Y%m%d%H%M%S")
end
def asset_timestamp
env.timestamp.strftime("%Y%m%d%H%M.%S")
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dsl/paths.rb | lib/capistrano/dsl/paths.rb | require "pathname"
module Capistrano
module DSL
module Paths
def deploy_to
fetch(:deploy_to)
end
def deploy_path
Pathname.new(deploy_to)
end
def current_path
deploy_path.join(fetch(:current_directory, "current"))
end
def releases_path
deploy_path.join(fetch(:releases_directory, "releases"))
end
def release_path
fetch(:release_path) { current_path }
end
def set_release_path(timestamp=now)
set(:release_timestamp, timestamp)
set(:release_path, releases_path.join(timestamp))
end
def stage_config_path
Pathname.new fetch(:stage_config_path, "config/deploy")
end
def deploy_config_path
Pathname.new fetch(:deploy_config_path, "config/deploy.rb")
end
def repo_url
fetch(:repo_url)
end
def repo_path
Pathname.new(fetch(:repo_path, ->() { deploy_path.join("repo") }))
end
def shared_path
deploy_path.join(fetch(:shared_directory, "shared"))
end
def revision_log
deploy_path.join("revisions.log")
end
def now
env.timestamp.strftime("%Y%m%d%H%M%S")
end
def asset_timestamp
env.timestamp.strftime("%Y%m%d%H%M.%S")
end
def linked_dirs(parent)
paths = fetch(:linked_dirs)
join_paths(parent, paths)
end
def linked_files(parent)
paths = fetch(:linked_files)
join_paths(parent, paths)
end
def linked_file_dirs(parent)
map_dirnames(linked_files(parent))
end
def linked_dir_parents(parent)
map_dirnames(linked_dirs(parent))
end
def join_paths(parent, paths)
paths.map { |path| parent.join(path) }
end
def map_dirnames(paths)
paths.map(&:dirname).uniq
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dsl/task_enhancements.rb | lib/capistrano/dsl/task_enhancements.rb | require "capistrano/upload_task"
module Capistrano
module TaskEnhancements
def before(task, prerequisite, *args, &block)
prerequisite = Rake::Task.define_task(prerequisite, *args, &block) if block_given?
Rake::Task[task].enhance [prerequisite]
end
def after(task, post_task, *args, &block)
Rake::Task.define_task(post_task, *args, &block) if block_given?
task = Rake::Task[task]
task.enhance do
post = Rake.application.lookup(post_task, task.scope)
raise ArgumentError, "Task #{post_task.inspect} not found" unless post
post.invoke
end
end
def define_remote_file_task(task, target_roles)
Capistrano::UploadTask.define_task(task) do |t|
prerequisite_file = t.prerequisites.first
file = shared_path.join(t.name)
on roles(target_roles) do
unless test "[ -f #{file.to_s.shellescape} ]"
info "Uploading #{prerequisite_file} to #{file}"
upload! File.open(prerequisite_file), file
end
end
end
end
def ensure_stage
Rake::Task.define_task(:ensure_stage) do
unless stage_set?
puts t(:stage_not_set)
exit 1
end
end
end
def tasks_without_stage_dependency
stages + default_tasks
end
def default_tasks
%w{install}
end
def exit_deploy_because_of_exception(ex)
warn t(:deploy_failed, ex: ex.message)
invoke "deploy:failed"
exit(false)
end
def deploying?
fetch(:deploying, false)
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/plugin_installer.rb | lib/capistrano/configuration/plugin_installer.rb | # Encapsulates the logic for installing plugins into Capistrano. Plugins must
# simply conform to a basic API; the PluginInstaller takes care of invoking the
# API at appropriate times.
#
# This class is not used directly; instead it is typically accessed via the
# `install_plugin` method of the Capistrano DSL.
#
module Capistrano
class Configuration
class PluginInstaller
# "Installs" a Plugin into Capistrano by loading its tasks, hooks, and
# defaults at the appropriate time. The hooks in particular can be
# skipped, if you want full control over when and how the plugin's tasks
# are executed. Simply pass `load_hooks:false` to opt out.
#
# The plugin class or instance may be provided. These are equivalent:
#
# install(Capistrano::SCM::Git)
# install(Capistrano::SCM::Git.new)
#
# Note that the :load_immediately flag is for internal use only and will
# be removed in an upcoming release.
#
def install(plugin, load_hooks: true, load_immediately: false)
plugin = plugin.is_a?(Class) ? plugin.new : plugin
plugin.define_tasks
plugin.register_hooks if load_hooks
@scm_installed ||= provides_scm?(plugin)
if load_immediately
plugin.set_defaults
else
Rake::Task.define_task("load:defaults") do
plugin.set_defaults
end
end
end
def scm_installed?
@scm_installed
end
private
def provides_scm?(plugin)
plugin.respond_to?(:scm?) && plugin.scm?
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/servers.rb | lib/capistrano/configuration/servers.rb | require "set"
require "capistrano/configuration"
require "capistrano/configuration/filter"
module Capistrano
class Configuration
class Servers
include Enumerable
def add_host(host, properties={})
new_host = Server[host]
new_host.port = properties[:port] if properties.key?(:port)
# This matching logic must stay in sync with `Server#matches?`.
key = ServerKey.new(new_host.hostname, new_host.port)
existing = servers_by_key[key]
if existing
existing.user = new_host.user if new_host.user
existing.with(properties)
else
servers_by_key[key] = new_host.with(properties)
end
end
# rubocop:disable Security/MarshalLoad
def add_role(role, hosts, options={})
options_deepcopy = Marshal.dump(options.merge(roles: role))
Array(hosts).each { |host| add_host(host, Marshal.load(options_deepcopy)) }
end
# rubocop:enable Security/MarshalLoad
def roles_for(names)
options = extract_options(names)
s = Filter.new(:role, names).filter(servers_by_key.values)
s.select { |server| server.select?(options) }
end
def role_properties_for(rolenames)
roles = rolenames.to_set
rps = Set.new unless block_given?
roles_for(rolenames).each do |host|
host.roles.intersection(roles).each do |role|
[host.properties.fetch(role)].flatten(1).each do |props|
if block_given?
yield host, role, props
else
rps << (props || {}).merge(role: role, hostname: host.hostname)
end
end
end
end
block_given? ? nil : rps
end
def fetch_primary(role)
hosts = roles_for([role])
hosts.find(&:primary) || hosts.first
end
def each
servers_by_key.values.each { |server| yield server }
end
private
ServerKey = Struct.new(:hostname, :port)
def servers_by_key
@servers_by_key ||= {}
end
def extract_options(array)
array.last.is_a?(::Hash) ? array.pop : {}
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/null_filter.rb | lib/capistrano/configuration/null_filter.rb | module Capistrano
class Configuration
class NullFilter
def filter(servers)
servers
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/host_filter.rb | lib/capistrano/configuration/host_filter.rb | module Capistrano
class Configuration
class HostFilter
def initialize(values)
av = Array(values).dup
av = av.flat_map { |v| v.is_a?(String) && v =~ /^(?<name>[-A-Za-z0-9.]+)(,\g<name>)*$/ ? v.split(",") : v }
@rex = regex_matcher(av)
end
def filter(servers)
Array(servers).select { |s| @rex.match s.to_s }
end
private
def regex_matcher(values)
values.map! do |v|
case v
when Regexp then v
else
vs = v.to_s
vs =~ /^[-A-Za-z0-9.]+$/ ? /^#{Regexp.quote(vs)}$/ : Regexp.new(vs)
end
end
Regexp.union values
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/variables.rb | lib/capistrano/configuration/variables.rb | require "capistrano/proc_helpers"
module Capistrano
class Configuration
# Holds the variables assigned at Capistrano runtime via `set` and retrieved
# with `fetch`. Does internal bookkeeping to help identify user mistakes
# like spelling errors or unused variables that may lead to unexpected
# behavior.
class Variables
CAPISTRANO_LOCATION = File.expand_path("../..", __FILE__).freeze
IGNORED_LOCATIONS = [
"#{CAPISTRANO_LOCATION}/configuration/variables.rb:",
"#{CAPISTRANO_LOCATION}/configuration.rb:",
"#{CAPISTRANO_LOCATION}/dsl/env.rb:",
"/dsl.rb:",
"/forwardable.rb:"
].freeze
private_constant :CAPISTRANO_LOCATION, :IGNORED_LOCATIONS
include Capistrano::ProcHelpers
def initialize(values={})
@trusted_keys = []
@fetched_keys = []
@locations = {}
@values = values
@trusted = true
end
def untrusted!
@trusted = false
yield
ensure
@trusted = true
end
def set(key, value=nil, &block)
@trusted_keys << key if trusted? && !@trusted_keys.include?(key)
remember_location(key)
values[key] = block || value
trace_set(key)
values[key]
end
def fetch(key, default=nil, &block)
fetched_keys << key unless fetched_keys.include?(key)
peek(key, default, &block)
end
# Internal use only.
def peek(key, default=nil, &block)
value = fetch_for(key, default, &block)
while callable_without_parameters?(value)
value = (values[key] = value.call)
end
value
end
def fetch_for(key, default, &block)
block ? values.fetch(key, &block) : values.fetch(key, default)
end
def delete(key)
values.delete(key)
end
def trusted_keys
@trusted_keys.dup
end
def untrusted_keys
keys - @trusted_keys
end
def keys
values.keys
end
# Keys that have been set, but which have never been fetched.
def unused_keys
keys - fetched_keys
end
# Returns an array of source file location(s) where the given key was
# assigned (i.e. where `set` was called). If the key was never assigned,
# returns `nil`.
def source_locations(key)
locations[key]
end
private
attr_reader :locations, :values, :fetched_keys
def trusted?
@trusted
end
def remember_location(key)
location = caller.find do |line|
IGNORED_LOCATIONS.none? { |i| line.include?(i) }
end
(locations[key] ||= []) << location
end
def trace_set(key)
return unless fetch(:print_config_variables, false)
puts "Config variable set: #{key.inspect} => #{values[key].inspect}"
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/filter.rb | lib/capistrano/configuration/filter.rb | require "capistrano/configuration"
require "capistrano/configuration/empty_filter"
require "capistrano/configuration/host_filter"
require "capistrano/configuration/null_filter"
require "capistrano/configuration/role_filter"
module Capistrano
class Configuration
class Filter
def initialize(type, values=nil)
raise "Invalid filter type #{type}" unless %i(host role).include? type
av = Array(values)
@strategy = if av.empty? then EmptyFilter.new
elsif av.include?(:all) || av.include?("all") then NullFilter.new
elsif type == :host then HostFilter.new(values)
elsif type == :role then RoleFilter.new(values)
else NullFilter.new
end
end
def filter(servers)
@strategy.filter servers
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/role_filter.rb | lib/capistrano/configuration/role_filter.rb | module Capistrano
class Configuration
class RoleFilter
def initialize(values)
av = Array(values).dup
av = av.flat_map { |v| v.is_a?(String) ? v.split(",") : v }
@rex = regex_matcher(av)
end
def filter(servers)
Array(servers).select { |s| s.is_a?(String) ? false : s.roles.any? { |r| @rex.match r } }
end
private
def regex_matcher(values)
values.map! do |v|
case v
when Regexp then v
else
vs = v.to_s
vs =~ %r{^/(.+)/$} ? Regexp.new($1) : /^#{Regexp.quote(vs)}$/
end
end
Regexp.union values
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/empty_filter.rb | lib/capistrano/configuration/empty_filter.rb | module Capistrano
class Configuration
class EmptyFilter
def filter(_servers)
[]
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/question.rb | lib/capistrano/configuration/question.rb | module Capistrano
class Configuration
class Question
def initialize(key, default, options={})
@key = key
@default = default
@options = options
end
def call
ask_question
value_or_default
end
private
attr_reader :key, :default, :options
def ask_question
$stdout.print question
$stdout.flush
end
def value_or_default
if response.empty?
default
else
response
end
end
def response
return @response if defined? @response
@response = (gets || "").chomp
end
def gets
return unless stdin.tty?
if echo?
stdin.gets
else
stdin.noecho(&:gets).tap { $stdout.print "\n" }
end
rescue Errno::EIO
# when stdio gets closed
return
end
def question
if prompt && default.nil?
I18n.t(:question_prompt, key: prompt, scope: :capistrano)
elsif prompt
I18n.t(:question_prompt_default, key: prompt, default_value: default, scope: :capistrano)
elsif default.nil?
I18n.t(:question, key: key, scope: :capistrano)
else
I18n.t(:question_default, key: key, default_value: default, scope: :capistrano)
end
end
def echo?
(options || {}).fetch(:echo, true)
end
def stdin
(options || {}).fetch(:stdin, $stdin)
end
def prompt
(options || {}).fetch(:prompt, nil)
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/server.rb | lib/capistrano/configuration/server.rb | require "set"
module Capistrano
class Configuration
class Server < SSHKit::Host
extend Forwardable
def_delegators :properties, :roles, :fetch, :set
def self.[](host)
host.is_a?(Server) ? host : new(host)
end
def add_roles(roles)
Array(roles).each { |role| add_role(role) }
self
end
alias roles= add_roles
def add_role(role)
roles.add role.to_sym
self
end
def has_role?(role)
roles.include? role.to_sym
end
def select?(options)
options.each do |k, v|
callable = v.respond_to?(:call) ? v : ->(server) { server.fetch(v) }
result = \
case k
when :filter, :select
callable.call(self)
when :exclude
!callable.call(self)
else
fetch(k) == v
end
return false unless result
end
true
end
def primary
self if fetch(:primary)
end
def with(properties)
properties.each { |key, value| add_property(key, value) }
self
end
def properties
@properties ||= Properties.new
end
def netssh_options
@netssh_options ||= super.merge(fetch(:ssh_options) || {})
end
def roles_array
roles.to_a
end
def matches?(other)
# This matching logic must stay in sync with `Servers#add_host`.
hostname == other.hostname && port == other.port
end
private
def add_property(key, value)
if respond_to?("#{key}=")
send("#{key}=", value)
else
set(key, value)
end
end
class Properties
def initialize
@properties = {}
end
def set(key, value)
pval = @properties[key]
if pval.is_a?(Hash) && value.is_a?(Hash)
pval.merge!(value)
elsif pval.is_a?(Set) && value.is_a?(Set)
pval.merge(value)
elsif pval.is_a?(Array) && value.is_a?(Array)
pval.concat value
else
@properties[key] = value
end
end
def fetch(key)
@properties[key]
end
def respond_to_missing?(method, _include_all=false)
@properties.key?(method) || super
end
def roles
@roles ||= Set.new
end
def keys
@properties.keys
end
def method_missing(key, value=nil)
if value
set(lvalue(key), value)
else
fetch(key)
end
end
def to_h
@properties
end
private
def lvalue(key)
key.to_s.chomp("=").to_sym
end
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/validated_variables.rb | lib/capistrano/configuration/validated_variables.rb | require "capistrano/proc_helpers"
require "delegate"
module Capistrano
class Configuration
# Decorates a Variables object to additionally perform an optional set of
# user-supplied validation rules. Each rule for a given key is invoked
# immediately whenever `set` is called with a value for that key.
#
# If `set` is called with a callable value or a block, validation is not
# performed immediately. Instead, the validation rules are invoked the first
# time `fetch` is used to access the value.
#
# A rule is simply a block that accepts two arguments: key and value. It is
# up to the rule to raise an exception when it deems the value is invalid
# (or just print a warning).
#
# Rules can be registered using the DSL like this:
#
# validate(:my_key) do |key, value|
# # rule goes here
# end
#
class ValidatedVariables < SimpleDelegator
include Capistrano::ProcHelpers
def initialize(variables)
super(variables)
@validators = {}
end
# Decorate Variables#set to add validation behavior.
def set(key, value=nil, &block)
assert_value_or_block_not_both(value, block)
# Skip validation behavior if no validators are registered for this key
return super unless validators.key?(key)
value_to_evaluate = block || value
if callable_without_parameters?(value_to_evaluate)
super(key, assert_valid_later(key, value_to_evaluate), &nil)
else
assert_valid_now(key, value_to_evaluate)
super
end
end
# Register a validation rule for the given key.
def validate(key, &validator)
vs = (validators[key] || [])
vs << validator
validators[key] = vs
end
private
attr_reader :validators
# Given a callable that provides a value, wrap the callable with another
# object that responds to `call`. This new object will perform validation
# and then return the original callable's value.
#
# If the callable is a `Question`, the object returned by this method will
# also be a `Question` (a `ValidatedQuestion`, to be precise). This
# ensures that `is_a?(Question)` remains true even after the validation
# wrapper is applied. This is needed so that `Configuration#is_question?`
# works as expected.
#
def assert_valid_later(key, callable)
validation_callback = proc do
value = callable.call
assert_valid_now(key, value)
value
end
if callable.is_a?(Question)
ValidatedQuestion.new(validation_callback)
else
validation_callback
end
end
# Runs all validation rules registered for the given key against the
# user-supplied value for that variable. If no validator raises an
# exception, the value is assumed to be valid.
def assert_valid_now(key, value)
validators[key].each do |validator|
validator.call(key, value)
end
end
def assert_value_or_block_not_both(value, block)
return if value.nil? || block.nil?
raise Capistrano::ValidationError,
"Value and block both passed to Configuration#set"
end
class ValidatedQuestion < Question
def initialize(validator)
@validator = validator
end
def call
@validator.call
end
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration/scm_resolver.rb | lib/capistrano/configuration/scm_resolver.rb | module Capistrano
class Configuration
# In earlier versions of Capistrano, users would specify the desired SCM
# implementation using `set :scm, :git`, for example. Capistrano would then
# load the matching .rb file based on this variable.
#
# Now we expect users to explicitly `require` and call `new` on the desired
# SCM implementation in their Capfile. The `set` technique is deprecated.
#
# This SCMResolver class takes care of managing the transition from the old
# to new system. It maintains the legacy behavior, but prints deprecation
# warnings when it is used.
#
# To maintain backwards compatibility, the resolver will load the Git SCM by
# if default it determines that no SCM has been explicitly specified or
# loaded. To force no SCM to be used at all, use `set :scm, nil`. This hack
# won't be necessary once backwards compatibility is removed in a future
# version.
#
# TODO: Remove this class entirely in Capistrano 4.0.
#
class SCMResolver
DEFAULT_GIT = :"default-git"
include Capistrano::DSL
def resolve
return if scm_name.nil?
set(:scm, :git) if using_default_scm?
print_deprecation_warnings_if_applicable
# Note that `scm_plugin_installed?` comes from Capistrano::DSL
if scm_plugin_installed?
delete(:scm)
return
end
if built_in_scm_name?
load_built_in_scm
else
# Compatibility with existing 3.x third-party SCMs
register_legacy_scm_hooks
load_legacy_scm_by_name
end
end
private
def using_default_scm?
return @using_default_scm if defined? @using_default_scm
@using_default_scm = (fetch(:scm) == DEFAULT_GIT)
end
def scm_name
fetch(:scm)
end
def load_built_in_scm
require "capistrano/scm/#{scm_name}"
scm_class = Object.const_get(built_in_scm_plugin_class_name)
# We use :load_immediately because we are initializing the SCM plugin
# late in the load process and therefore can't use the standard
# load:defaults technique.
install_plugin(scm_class, load_immediately: true)
end
def load_legacy_scm_by_name
load("capistrano/#{scm_name}.rb")
end
def third_party_scm_name?
!built_in_scm_name?
end
def built_in_scm_name?
%w(git hg svn).include?(scm_name.to_s.downcase)
end
def built_in_scm_plugin_class_name
"Capistrano::SCM::#{scm_name.to_s.capitalize}"
end
# rubocop:disable Style/GuardClause
def register_legacy_scm_hooks
if Rake::Task.task_defined?("deploy:new_release_path")
after "deploy:new_release_path", "#{scm_name}:create_release"
end
if Rake::Task.task_defined?("deploy:check")
before "deploy:check", "#{scm_name}:check"
end
if Rake::Task.task_defined?("deploy:set_current_revision")
before "deploy:set_current_revision",
"#{scm_name}:set_current_revision"
end
end
# rubocop:enable Style/GuardClause
def print_deprecation_warnings_if_applicable
if using_default_scm?
warn_add_git_to_capfile unless scm_plugin_installed?
elsif built_in_scm_name?
warn_set_scm_is_deprecated
elsif third_party_scm_name?
warn_third_party_scm_must_be_upgraded
end
end
def warn_set_scm_is_deprecated
$stderr.puts(<<-MESSAGE)
[Deprecation Notice] `set :scm, #{scm_name.inspect}` is deprecated.
To ensure your project is compatible with future versions of Capistrano,
remove the :scm setting and instead add these lines to your Capfile after
`require "capistrano/deploy"`:
require "capistrano/scm/#{scm_name}"
install_plugin #{built_in_scm_plugin_class_name}
MESSAGE
end
def warn_add_git_to_capfile
$stderr.puts(<<-MESSAGE)
[Deprecation Notice] Future versions of Capistrano will not load the Git SCM
plugin by default. To silence this deprecation warning, add the following to
your Capfile after `require "capistrano/deploy"`:
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git
MESSAGE
end
def warn_third_party_scm_must_be_upgraded
$stderr.puts(<<-MESSAGE)
[Deprecation Notice] `set :scm, #{scm_name.inspect}` is deprecated.
To ensure this custom SCM will work with future versions of Capistrano,
please upgrade it to a version that uses the new SCM plugin mechanism
documented here:
http://capistranorb.com/documentation/advanced-features/custom-scm
MESSAGE
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor/output_helpers.rb | lib/capistrano/doctor/output_helpers.rb | module Capistrano
module Doctor
# Helper methods for pretty-printing doctor output to stdout. All output
# (other than `title`) is indented by four spaces to facilitate copying and
# pasting this output into e.g. GitHub or Stack Overflow to achieve code
# formatting.
module OutputHelpers
class Row
attr_reader :color
attr_reader :values
def initialize
@values = []
end
def <<(value)
values << value
end
def yellow
@color = :yellow
end
end
# Prints a table for a given array of records. For each record, the block
# is yielded two arguments: the record and a Row object. To print values
# for that record, add values using `row << "some value"`. A row can
# optionally be highlighted in yellow using `row.yellow`.
def table(records, &block)
return if records.empty?
rows = collect_rows(records, &block)
col_widths = calculate_column_widths(rows)
rows.each do |row|
line = row.values.each_with_index.map do |value, col|
value.to_s.ljust(col_widths[col])
end.join(" ").rstrip
line = color.colorize(line, row.color) if row.color
puts line
end
end
# Prints a title in blue with surrounding newlines.
def title(text)
# Use $stdout directly to bypass the indentation that our `puts` does.
$stdout.puts(color.colorize("\n#{text}\n", :blue))
end
# Prints text in yellow.
def warning(text)
puts color.colorize(text, :yellow)
end
# Override `Kernel#puts` to prepend four spaces to each line.
def puts(string=nil)
$stdout.puts(string.to_s.gsub(/^/, " "))
end
private
def collect_rows(records)
records.map do |rec|
Row.new.tap { |row| yield(rec, row) }
end
end
def calculate_column_widths(rows)
num_columns = rows.map { |row| row.values.length }.max
Array.new(num_columns) do |col|
rows.map { |row| row.values[col].to_s.length }.max
end
end
def color
@color ||= SSHKit::Color.new($stdout)
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor/environment_doctor.rb | lib/capistrano/doctor/environment_doctor.rb | require "capistrano/doctor/output_helpers"
module Capistrano
module Doctor
class EnvironmentDoctor
include Capistrano::Doctor::OutputHelpers
def call
title("Environment")
puts <<-OUT.gsub(/^\s+/, "")
Ruby #{RUBY_DESCRIPTION}
Rubygems #{Gem::VERSION}
Bundler #{defined?(Bundler::VERSION) ? Bundler::VERSION : 'N/A'}
Command #{$PROGRAM_NAME} #{ARGV.join(' ')}
OUT
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor/servers_doctor.rb | lib/capistrano/doctor/servers_doctor.rb | require "capistrano/doctor/output_helpers"
module Capistrano
module Doctor
class ServersDoctor
include Capistrano::Doctor::OutputHelpers
def initialize(env=Capistrano::Configuration.env)
@servers = env.servers.to_a
end
def call
title("Servers (#{servers.size})")
rwc = RoleWhitespaceChecker.new(servers)
table(servers) do |server, row|
sd = ServerDecorator.new(server)
row << sd.uri_form
row << sd.roles
row << sd.properties
row.yellow if rwc.any_has_whitespace?(server.roles)
end
if rwc.whitespace_roles.any?
warning "\nWhitespace detected in role(s) #{rwc.whitespace_roles_decorated}. " \
"This might be a result of a mistyped \"%w()\" array literal."
end
puts
end
private
attr_reader :servers
class RoleWhitespaceChecker
attr_reader :whitespace_roles, :servers
def initialize(servers)
@servers = servers
@whitespace_roles = find_whitespace_roles
end
def any_has_whitespace?(roles)
roles.any? { |role| include_whitespace?(role) }
end
def include_whitespace?(role)
role =~ /\s/
end
def whitespace_roles_decorated
whitespace_roles.map(&:inspect).join(", ")
end
private
def find_whitespace_roles
servers.map(&:roles).flat_map(&:to_a).uniq
.select { |role| include_whitespace?(role) }
end
end
class ServerDecorator
def initialize(server)
@server = server
end
def uri_form
[
server.user,
server.user && "@",
server.hostname,
server.port && ":",
server.port
].compact.join
end
def roles
server.roles.to_a.inspect
end
def properties
return "" unless server.properties.keys.any?
pretty_inspect(server.properties.to_h)
end
private
attr_reader :server
# Hashes with proper padding
def pretty_inspect(element)
return element.inspect unless element.is_a?(Hash)
pairs_string = element.keys.map do |key|
[pretty_inspect(key), pretty_inspect(element.fetch(key))].join(" => ")
end.join(", ")
"{ #{pairs_string} }"
end
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor/variables_doctor.rb | lib/capistrano/doctor/variables_doctor.rb | require "capistrano/doctor/output_helpers"
module Capistrano
module Doctor
# Prints a table of all Capistrano variables and their current values. If
# there are unrecognized variables, print warnings for them.
class VariablesDoctor
# These are keys that are recognized by Capistrano, but do not have values
# set by default.
WHITELIST = %i(
application
current_directory
linked_dirs
linked_files
releases_directory
repo_url
repo_tree
shared_directory
).freeze
private_constant :WHITELIST
include Capistrano::Doctor::OutputHelpers
def initialize(env=Capistrano::Configuration.env)
@env = env
end
def call
title("Variables")
values = inspect_all_values
table(variables.keys.sort_by(&:to_s)) do |key, row|
row.yellow if suspicious_keys.include?(key)
row << key.inspect
row << values[key]
end
puts if suspicious_keys.any?
suspicious_keys.sort_by(&:to_s).each do |key|
warning("#{key.inspect} is not a recognized Capistrano setting "\
"(#{location(key)})")
end
end
private
attr_reader :env
def variables
env.variables
end
def inspect_all_values
variables.keys.each_with_object({}) do |key, inspected|
inspected[key] = if env.is_question?(key)
"<ask>"
else
variables.peek(key).inspect
end
end
end
def suspicious_keys
(variables.untrusted_keys & variables.unused_keys) - WHITELIST
end
def location(key)
loc = variables.source_locations(key).first
loc && loc.sub(/^#{Regexp.quote(Dir.pwd)}/, "").sub(/:in.*/, "")
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor/gems_doctor.rb | lib/capistrano/doctor/gems_doctor.rb | require "capistrano/doctor/output_helpers"
module Capistrano
module Doctor
# Prints table of all Capistrano-related gems and their version numbers. If
# there is a newer version of a gem available, call attention to it.
class GemsDoctor
include Capistrano::Doctor::OutputHelpers
def call
title("Gems")
table(all_gem_names) do |gem, row|
row.yellow if update_available?(gem)
row << gem
row << installed_gem_version(gem)
row << "(update available)" if update_available?(gem)
end
end
private
def installed_gem_version(gem_name)
Gem.loaded_specs[gem_name].version
end
def update_available?(gem_name)
latest = Gem.latest_version_for(gem_name)
return false if latest.nil?
latest > installed_gem_version(gem_name)
end
def all_gem_names
core_gem_names + plugin_gem_names
end
def core_gem_names
%w(capistrano airbrussh rake sshkit net-ssh) & Gem.loaded_specs.keys
end
def plugin_gem_names
(Gem.loaded_specs.keys - ["capistrano"]).grep(/capistrano/).sort
end
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/scm/plugin.rb | lib/capistrano/scm/plugin.rb | require "capistrano/plugin"
require "capistrano/scm"
# Base class for all built-in and third-party SCM plugins. Notice that this
# class doesn't really do anything other than provide an `scm?` predicate. This
# tells Capistrano that the plugin provides SCM functionality. All other plugin
# features are inherited from Capistrano::Plugin.
#
class Capistrano::SCM::Plugin < Capistrano::Plugin
def scm?
true
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/scm/svn.rb | lib/capistrano/scm/svn.rb | require "capistrano/scm/plugin"
class Capistrano::SCM::Svn < Capistrano::SCM::Plugin
def register_hooks
after "deploy:new_release_path", "svn:create_release"
before "deploy:check", "svn:check"
before "deploy:set_current_revision", "svn:set_current_revision"
end
def define_tasks
eval_rakefile File.expand_path("../tasks/svn.rake", __FILE__)
end
def svn(*args)
args.unshift(:svn)
args.push "--username #{fetch(:svn_username)}" if fetch(:svn_username)
args.push "--password #{fetch(:svn_password)}" if fetch(:svn_password)
args.push "--revision #{fetch(:svn_revision)}" if fetch(:svn_revision)
backend.execute(*args)
end
def repo_mirror_exists?
backend.test " [ -d #{repo_path}/.svn ] "
end
def check_repo_is_reachable
svn_username = fetch(:svn_username) ? "--username #{fetch(:svn_username)}" : ""
svn_password = fetch(:svn_password) ? "--password #{fetch(:svn_password)}" : ""
backend.test :svn, :info, repo_url, svn_username, svn_password
end
def clone_repo
svn :checkout, repo_url, repo_path.to_s
end
def update_mirror
# Switch the repository URL if necessary.
repo_mirror_url = fetch_repo_mirror_url
svn :switch, repo_url unless repo_mirror_url == repo_url
svn :update
end
def archive_to_release_path
svn :export, "--force", ".", release_path
end
def fetch_revision
backend.capture(:svnversion, repo_path.to_s)
end
def fetch_repo_mirror_url
backend.capture(:svn, :info, repo_path.to_s).each_line do |line|
return $1 if /\AURL: (.*)\n\z/ =~ line
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/scm/hg.rb | lib/capistrano/scm/hg.rb | require "capistrano/scm/plugin"
require "securerandom"
class Capistrano::SCM::Hg < Capistrano::SCM::Plugin
def register_hooks
after "deploy:new_release_path", "hg:create_release"
before "deploy:check", "hg:check"
before "deploy:set_current_revision", "hg:set_current_revision"
end
def define_tasks
eval_rakefile File.expand_path("../tasks/hg.rake", __FILE__)
end
def hg(*args)
args.unshift(:hg)
backend.execute(*args)
end
def repo_mirror_exists?
backend.test " [ -d #{repo_path}/.hg ] "
end
def check_repo_is_reachable
hg "id", repo_url
end
def clone_repo
hg "clone", "--noupdate", repo_url, repo_path.to_s
end
def update_mirror
hg "pull"
end
def archive_to_release_path
if (tree = fetch(:repo_tree))
tree = tree.slice %r#^/?(.*?)/?$#, 1
components = tree.split("/").size
temp_tar = "#{fetch(:tmp_dir)}/#{SecureRandom.hex(10)}.tar"
hg "archive -p . -I", tree, "--rev", fetch(:branch), temp_tar
backend.execute :mkdir, "-p", release_path
backend.execute :tar, "-x --strip-components #{components} -f", temp_tar, "-C", release_path
backend.execute :rm, temp_tar
else
hg "archive", release_path, "--rev", fetch(:branch)
end
end
def fetch_revision
backend.capture(:hg, "log --rev #{fetch(:branch)} --template \"{node}\n\"")
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
capistrano/capistrano | https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/scm/git.rb | lib/capistrano/scm/git.rb | require "capistrano/scm/plugin"
require "cgi"
require "securerandom"
require "shellwords"
require "stringio"
require "uri"
class Capistrano::SCM::Git < Capistrano::SCM::Plugin
def set_defaults
set_if_empty :git_shallow_clone, false
set_if_empty :git_wrapper_path, lambda {
# Use a unique name that won't collide with other deployments, and
# that cannot be guessed by other processes that have access to /tmp.
"#{fetch(:tmp_dir)}/git-ssh-#{SecureRandom.hex(10)}.sh"
}
set_if_empty :git_environmental_variables, lambda {
{
git_askpass: "/bin/echo",
git_ssh: fetch(:git_wrapper_path)
}
}
set_if_empty :git_max_concurrent_connections, 10
set_if_empty :git_wait_interval, 0
end
def register_hooks
after "deploy:new_release_path", "git:create_release"
before "deploy:check", "git:check"
before "deploy:set_current_revision", "git:set_current_revision"
before "deploy:set_current_revision_time", "git:set_current_revision_time"
end
def define_tasks
eval_rakefile File.expand_path("../tasks/git.rake", __FILE__)
end
def repo_mirror_exists?
backend.test " [ -f #{repo_path}/HEAD ] "
end
def check_repo_is_reachable
git :'ls-remote', git_repo_url, "HEAD"
end
def clone_repo
if (depth = fetch(:git_shallow_clone))
git :clone, "--mirror", "--depth", depth, "--no-single-branch", git_repo_url, repo_path.to_s
else
git :clone, "--mirror", git_repo_url, repo_path.to_s
end
end
def update_mirror
# Update the origin URL if necessary.
git :remote, "set-url", "origin", git_repo_url
# Note: Requires git version 1.9 or greater
if (depth = fetch(:git_shallow_clone))
git :fetch, "--depth", depth, "origin", fetch(:branch)
else
git :remote, :update, "--prune"
end
end
def verify_commit
git :"verify-commit", fetch_revision
end
def archive_to_release_path
if (tree = fetch(:repo_tree))
tree = tree.slice %r#^/?(.*?)/?$#, 1
components = tree.split("/").size
git :archive, fetch(:branch), tree, "| #{SSHKit.config.command_map[:tar]} -x --strip-components #{components} -f - -C", release_path
else
git :archive, fetch(:branch), "| #{SSHKit.config.command_map[:tar]} -x -f - -C", release_path
end
end
def fetch_revision
backend.capture(:git, "rev-list --max-count=1 #{fetch(:branch)}")
end
def fetch_revision_time
backend.capture(:git, "--no-pager log -1 --pretty=format:\"%ct\" #{fetch(:branch)}")
end
def git(*args)
args.unshift :git
backend.execute(*args)
end
def git_repo_url
if fetch(:git_http_username) && fetch(:git_http_password)
URI.parse(repo_url).tap do |repo_uri|
repo_uri.user = fetch(:git_http_username)
repo_uri.password = CGI.escape(fetch(:git_http_password))
end.to_s
elsif fetch(:git_http_username)
URI.parse(repo_url).tap do |repo_uri|
repo_uri.user = fetch(:git_http_username)
end.to_s
else
repo_url
end
end
end
| ruby | MIT | dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334 | 2026-01-04T15:37:35.862177Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/helpers/devise_helper.rb | app/helpers/devise_helper.rb | # frozen_string_literal: true
# Keeping the helper around for backward compatibility.
module DeviseHelper
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise_controller.rb | app/controllers/devise_controller.rb | # frozen_string_literal: true
# All Devise controllers are inherited from here.
class DeviseController < Devise.parent_controller.constantize
include Devise::Controllers::ScopedViews
if respond_to?(:helper)
helper DeviseHelper
end
if respond_to?(:helper_method)
helpers = %w(resource scope_name resource_name signed_in_resource
resource_class resource_params devise_mapping)
helper_method(*helpers)
end
prepend_before_action :assert_is_devise_resource!
self.responder = Devise.responder
respond_to :html if mimes_for_respond_to.empty?
# Override prefixes to consider the scoped view.
# Notice we need to check for the request due to a bug in
# Action Controller tests that forces _prefixes to be
# loaded before even having a request object.
#
# This method should be public as it is in ActionPack
# itself. Changing its visibility may break other gems.
def _prefixes #:nodoc:
@_prefixes ||= if self.class.scoped_views? && request && devise_mapping
["#{devise_mapping.scoped_path}/#{controller_name}"] + super
else
super
end
end
# Override internal methods to exclude `_prefixes` from action methods since
# we override it above.
#
# There was an intentional change in Rails 7.1 that will allow it to become
# an action method because it's a public method of a non-abstract controller,
# but we also can't make this abstract because it can affect potential actions
# defined in the parent controller, so instead we ensure `_prefixes` is going
# to be considered internal. (and thus, won't become an action method.)
# Ref: https://github.com/rails/rails/pull/48699
def self.internal_methods #:nodoc:
super << :_prefixes
end
protected
# Gets the actual resource stored in the instance variable
def resource
instance_variable_get(:"@#{resource_name}")
end
# Proxy to devise map name
def resource_name
devise_mapping.name
end
alias :scope_name :resource_name
# Proxy to devise map class
def resource_class
devise_mapping.to
end
# Returns a signed in resource from session (if one exists)
def signed_in_resource
warden.authenticate(scope: resource_name)
end
# Attempt to find the mapped route for devise based on request path
def devise_mapping
@devise_mapping ||= request.env["devise.mapping"]
end
# Checks whether it's a devise mapped resource or not.
def assert_is_devise_resource! #:nodoc:
unknown_action! <<-MESSAGE unless devise_mapping
Could not find devise mapping for path #{request.fullpath.inspect}.
This may happen for two reasons:
1) You forgot to wrap your route inside the scope block. For example:
devise_scope :user do
get "/some/route" => "some_devise_controller"
end
2) You are testing a Devise controller bypassing the router.
If so, you can explicitly tell Devise which mapping to use:
@request.env["devise.mapping"] = Devise.mappings[:user]
MESSAGE
end
# Returns real navigational formats which are supported by Rails
def navigational_formats
@navigational_formats ||= Devise.navigational_formats.select { |format| Mime::EXTENSION_LOOKUP[format.to_s] }
end
def unknown_action!(msg)
logger.debug "[Devise] #{msg}" if logger
raise AbstractController::ActionNotFound, msg
end
# Sets the resource creating an instance variable
def resource=(new_resource)
instance_variable_set(:"@#{resource_name}", new_resource)
end
# Helper for use in before_actions where no authentication is required.
#
# Example:
# before_action :require_no_authentication, only: :new
def require_no_authentication
assert_is_devise_resource!
return unless is_navigational_format?
no_input = devise_mapping.no_input_strategies
authenticated = if no_input.present?
args = no_input.dup.push scope: resource_name
warden.authenticate?(*args)
else
warden.authenticated?(resource_name)
end
if authenticated && resource = warden.user(resource_name)
set_flash_message(:alert, 'already_authenticated', scope: 'devise.failure')
redirect_to after_sign_in_path_for(resource)
end
end
# Helper for use after calling send_*_instructions methods on a resource.
# If we are in paranoid mode, we always act as if the resource was valid
# and instructions were sent.
def successfully_sent?(resource)
notice = if Devise.paranoid
resource.errors.clear
:send_paranoid_instructions
elsif resource.errors.empty?
:send_instructions
end
if notice
set_flash_message! :notice, notice
true
end
end
# Sets the flash message with :key, using I18n. By default you are able
# to set up your messages using specific resource scope, and if no message is
# found we look to the default scope. Set the "now" options key to a true
# value to populate the flash.now hash in lieu of the default flash hash (so
# the flash message will be available to the current action instead of the
# next action).
# Example (i18n locale file):
#
# en:
# devise:
# passwords:
# #default_scope_messages - only if resource_scope is not found
# user:
# #resource_scope_messages
#
# Please refer to README or en.yml locale file to check what messages are
# available.
def set_flash_message(key, kind, options = {})
message = find_message(kind, options)
if options[:now]
flash.now[key] = message if message.present?
else
flash[key] = message if message.present?
end
end
# Sets flash message if is_flashing_format? equals true
def set_flash_message!(key, kind, options = {})
if is_flashing_format?
set_flash_message(key, kind, options)
end
end
# Sets minimum password length to show to user
def set_minimum_password_length
if devise_mapping.validatable?
@minimum_password_length = resource_class.password_length.min
end
end
def devise_i18n_options(options)
options
end
# Get message for given
def find_message(kind, options = {})
options[:scope] ||= translation_scope
options[:default] = Array(options[:default]).unshift(kind.to_sym)
options[:resource_name] = resource_name
options = devise_i18n_options(options)
I18n.t("#{options[:resource_name]}.#{kind}", **options)
end
# Controllers inheriting DeviseController are advised to override this
# method so that other controllers inheriting from them would use
# existing translations.
def translation_scope
"devise.#{controller_name}"
end
def clean_up_passwords(object)
object.clean_up_passwords if object.respond_to?(:clean_up_passwords)
end
def respond_with_navigational(*args, &block)
respond_with(*args) do |format|
format.any(*navigational_formats, &block)
end
end
def resource_params
params.fetch(resource_name, {})
end
ActiveSupport.run_load_hooks(:devise_controller, self)
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/omniauth_callbacks_controller.rb | app/controllers/devise/omniauth_callbacks_controller.rb | # frozen_string_literal: true
class Devise::OmniauthCallbacksController < DeviseController
prepend_before_action { request.env["devise.skip_timeout"] = true }
def passthru
render status: 404, plain: "Not found. Authentication passthru."
end
def failure
set_flash_message! :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message
redirect_to after_omniauth_failure_path_for(resource_name)
end
protected
def failed_strategy
request.respond_to?(:get_header) ? request.get_header("omniauth.error.strategy") : request.env["omniauth.error.strategy"]
end
def failure_message
exception = request.respond_to?(:get_header) ? request.get_header("omniauth.error") : request.env["omniauth.error"]
error = exception.error_reason if exception.respond_to?(:error_reason)
error ||= exception.error if exception.respond_to?(:error)
error ||= (request.respond_to?(:get_header) ? request.get_header("omniauth.error.type") : request.env["omniauth.error.type"]).to_s
error.to_s.humanize if error
end
def after_omniauth_failure_path_for(scope)
new_session_path(scope)
end
def translation_scope
'devise.omniauth_callbacks'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/passwords_controller.rb | app/controllers/devise/passwords_controller.rb | # frozen_string_literal: true
class Devise::PasswordsController < DeviseController
prepend_before_action :require_no_authentication
# Render the #edit only if coming from a reset password email link
append_before_action :assert_reset_token_passed, only: :edit
# GET /resource/password/new
def new
self.resource = resource_class.new
end
# POST /resource/password
def create
self.resource = resource_class.send_reset_password_instructions(resource_params)
yield resource if block_given?
if successfully_sent?(resource)
respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name))
else
respond_with(resource)
end
end
# GET /resource/password/edit?reset_password_token=abcdef
def edit
self.resource = resource_class.new
set_minimum_password_length
resource.reset_password_token = params[:reset_password_token]
end
# PUT /resource/password
def update
self.resource = resource_class.reset_password_by_token(resource_params)
yield resource if block_given?
if resource.errors.empty?
resource.unlock_access! if unlockable?(resource)
if resource_class.sign_in_after_reset_password
flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
set_flash_message!(:notice, flash_message)
resource.after_database_authentication
sign_in(resource_name, resource)
else
set_flash_message!(:notice, :updated_not_active)
end
respond_with resource, location: after_resetting_password_path_for(resource)
else
set_minimum_password_length
respond_with resource
end
end
protected
def after_resetting_password_path_for(resource)
resource_class.sign_in_after_reset_password ? after_sign_in_path_for(resource) : new_session_path(resource_name)
end
# The path used after sending reset password instructions
def after_sending_reset_password_instructions_path_for(resource_name)
new_session_path(resource_name) if is_navigational_format?
end
# Check if a reset_password_token is provided in the request
def assert_reset_token_passed
if params[:reset_password_token].blank?
set_flash_message(:alert, :no_token)
redirect_to new_session_path(resource_name)
end
end
# Check if proper Lockable module methods are present & unlock strategy
# allows to unlock resource on password reset
def unlockable?(resource)
resource.respond_to?(:unlock_access!) &&
resource.respond_to?(:unlock_strategy_enabled?) &&
resource.unlock_strategy_enabled?(:email)
end
def translation_scope
'devise.passwords'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/unlocks_controller.rb | app/controllers/devise/unlocks_controller.rb | # frozen_string_literal: true
class Devise::UnlocksController < DeviseController
prepend_before_action :require_no_authentication
# GET /resource/unlock/new
def new
self.resource = resource_class.new
end
# POST /resource/unlock
def create
self.resource = resource_class.send_unlock_instructions(resource_params)
yield resource if block_given?
if successfully_sent?(resource)
respond_with({}, location: after_sending_unlock_instructions_path_for(resource))
else
respond_with(resource)
end
end
# GET /resource/unlock?unlock_token=abcdef
def show
self.resource = resource_class.unlock_access_by_token(params[:unlock_token])
yield resource if block_given?
if resource.errors.empty?
set_flash_message! :notice, :unlocked
respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) }
else
# TODO: use `error_status` when the default changes to `:unprocessable_entity` / `:unprocessable_content`.
respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
end
end
protected
# The path used after sending unlock password instructions
def after_sending_unlock_instructions_path_for(resource)
new_session_path(resource) if is_navigational_format?
end
# The path used after unlocking the resource
def after_unlock_path_for(resource)
new_session_path(resource) if is_navigational_format?
end
def translation_scope
'devise.unlocks'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/registrations_controller.rb | app/controllers/devise/registrations_controller.rb | # frozen_string_literal: true
class Devise::RegistrationsController < DeviseController
prepend_before_action :require_no_authentication, only: [:new, :create, :cancel]
prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy]
prepend_before_action :set_minimum_password_length, only: [:new, :edit]
# GET /resource/sign_up
def new
build_resource
yield resource if block_given?
respond_with resource
end
# POST /resource
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message! :notice, :signed_up
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
# GET /resource/edit
def edit
render :edit
end
# PUT /resource
# We need to use a copy of the resource because we don't want to change
# the current user in place.
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
resource_updated = update_resource(resource, account_update_params)
yield resource if block_given?
if resource_updated
set_flash_message_for_update(resource, prev_unconfirmed_email)
bypass_sign_in resource, scope: resource_name if sign_in_after_change_password?
respond_with resource, location: after_update_path_for(resource)
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
# DELETE /resource
def destroy
resource.destroy
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message! :notice, :destroyed
yield resource if block_given?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status }
end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
def cancel
expire_data_after_sign_in!
redirect_to new_registration_path(resource_name)
end
protected
def update_needs_confirmation?(resource, previous)
resource.respond_to?(:pending_reconfirmation?) &&
resource.pending_reconfirmation? &&
previous != resource.unconfirmed_email
end
# By default we want to require a password checks on update.
# You can overwrite this method in your own RegistrationsController.
def update_resource(resource, params)
resource.update_with_password(params)
end
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash = {})
self.resource = resource_class.new_with_session(hash, session)
end
# Signs in a user on sign up. You can overwrite this method in your own
# RegistrationsController.
def sign_up(resource_name, resource)
sign_in(resource_name, resource)
end
# The path used after sign up. You need to overwrite this method
# in your own RegistrationsController.
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource) if is_navigational_format?
end
# The path used after sign up for inactive accounts. You need to overwrite
# this method in your own RegistrationsController.
def after_inactive_sign_up_path_for(resource)
scope = Devise::Mapping.find_scope!(resource)
router_name = Devise.mappings[scope].router_name
context = router_name ? send(router_name) : self
context.respond_to?(:root_path) ? context.root_path : "/"
end
# The default url to be used after updating a resource. You need to overwrite
# this method in your own RegistrationsController.
def after_update_path_for(resource)
sign_in_after_change_password? ? signed_in_root_path(resource) : new_session_path(resource_name)
end
# Authenticates the current scope and gets the current resource from the session.
def authenticate_scope!
send(:"authenticate_#{resource_name}!", force: true)
self.resource = send(:"current_#{resource_name}")
end
def sign_up_params
devise_parameter_sanitizer.sanitize(:sign_up)
end
def account_update_params
devise_parameter_sanitizer.sanitize(:account_update)
end
def translation_scope
'devise.registrations'
end
private
def set_flash_message_for_update(resource, prev_unconfirmed_email)
return unless is_flashing_format?
flash_key = if update_needs_confirmation?(resource, prev_unconfirmed_email)
:update_needs_confirmation
elsif sign_in_after_change_password?
:updated
else
:updated_but_not_signed_in
end
set_flash_message :notice, flash_key
end
def sign_in_after_change_password?
return true if account_update_params[:password].blank?
Devise.sign_in_after_change_password
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/confirmations_controller.rb | app/controllers/devise/confirmations_controller.rb | # frozen_string_literal: true
class Devise::ConfirmationsController < DeviseController
# GET /resource/confirmation/new
def new
self.resource = resource_class.new
end
# POST /resource/confirmation
def create
self.resource = resource_class.send_confirmation_instructions(resource_params)
yield resource if block_given?
if successfully_sent?(resource)
respond_with({}, location: after_resending_confirmation_instructions_path_for(resource_name))
else
respond_with(resource)
end
end
# GET /resource/confirmation?confirmation_token=abcdef
def show
self.resource = resource_class.confirm_by_token(params[:confirmation_token])
yield resource if block_given?
if resource.errors.empty?
set_flash_message!(:notice, :confirmed)
respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
else
# TODO: use `error_status` when the default changes to `:unprocessable_entity` / `:unprocessable_content`.
respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
end
end
protected
# The path used after resending confirmation instructions.
def after_resending_confirmation_instructions_path_for(resource_name)
is_navigational_format? ? new_session_path(resource_name) : '/'
end
# The path used after confirmation.
def after_confirmation_path_for(resource_name, resource)
if signed_in?(resource_name)
signed_in_root_path(resource)
else
new_session_path(resource_name)
end
end
def translation_scope
'devise.confirmations'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/controllers/devise/sessions_controller.rb | app/controllers/devise/sessions_controller.rb | # frozen_string_literal: true
class Devise::SessionsController < DeviseController
prepend_before_action :require_no_authentication, only: [:new, :create]
prepend_before_action :allow_params_authentication!, only: :create
prepend_before_action :verify_signed_out_user, only: :destroy
prepend_before_action(only: [:create, :destroy]) { request.env["devise.skip_timeout"] = true }
# GET /resource/sign_in
def new
self.resource = resource_class.new(sign_in_params)
clean_up_passwords(resource)
yield resource if block_given?
respond_with(resource, serialize_options(resource))
end
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message!(:notice, :signed_in)
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
end
# DELETE /resource/sign_out
def destroy
signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
set_flash_message! :notice, :signed_out if signed_out
yield if block_given?
respond_to_on_destroy(non_navigational_status: :no_content)
end
protected
def sign_in_params
devise_parameter_sanitizer.sanitize(:sign_in)
end
def serialize_options(resource)
methods = resource_class.authentication_keys.dup
methods = methods.keys if methods.is_a?(Hash)
methods << :password if resource.respond_to?(:password)
{ methods: methods, only: [:password] }
end
def auth_options
{ scope: resource_name, recall: "#{controller_path}#new", locale: I18n.locale }
end
def translation_scope
'devise.sessions'
end
private
# Check if there is no signed in user before doing the sign out.
#
# If there is no signed in user, it will set the flash message and redirect
# to the after_sign_out path.
def verify_signed_out_user
if all_signed_out?
set_flash_message! :notice, :already_signed_out
respond_to_on_destroy(non_navigational_status: :unauthorized)
end
end
def all_signed_out?
users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
users.all?(&:blank?)
end
def respond_to_on_destroy(non_navigational_status: :no_content)
# We actually need to hardcode this as Rails default responder doesn't
# support returning empty response on GET request
respond_to do |format|
format.all { head non_navigational_status }
format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status }
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/app/mailers/devise/mailer.rb | app/mailers/devise/mailer.rb | # frozen_string_literal: true
if defined?(ActionMailer)
class Devise::Mailer < Devise.parent_mailer.constantize
include Devise::Mailers::Helpers
def confirmation_instructions(record, token, opts = {})
@token = token
devise_mail(record, :confirmation_instructions, opts)
end
def reset_password_instructions(record, token, opts = {})
@token = token
devise_mail(record, :reset_password_instructions, opts)
end
def unlock_instructions(record, token, opts = {})
@token = token
devise_mail(record, :unlock_instructions, opts)
end
def email_changed(record, opts = {})
devise_mail(record, :email_changed, opts)
end
def password_change(record, opts = {})
devise_mail(record, :password_change, opts)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/failure_app_test.rb | test/failure_app_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'ostruct'
class FailureTest < ActiveSupport::TestCase
class RootFailureApp < Devise::FailureApp
def fake_app
Object.new
end
end
class FailureWithSubdomain < RootFailureApp
routes = ActionDispatch::Routing::RouteSet.new
routes.draw do
scope subdomain: 'sub' do
root to: 'foo#bar'
end
end
include routes.url_helpers
end
class FailureWithI18nOptions < Devise::FailureApp
def i18n_options(options)
options.merge(name: 'Steve')
end
end
class FailureWithoutRootPath < Devise::FailureApp
class FakeURLHelpers
end
class FakeRoutesWithoutRoot
def url_helpers
FakeURLHelpers.new
end
end
class FakeAppWithoutRootPath
def routes
FakeRoutesWithoutRoot.new
end
end
def main_app
FakeAppWithoutRootPath.new
end
end
class FakeEngineApp < Devise::FailureApp
class FakeEngine
def new_user_on_engine_session_url _
'/user_on_engines/sign_in'
end
end
def main_app
raise 'main_app router called instead of fake_engine'
end
def fake_engine
@fake_engine ||= FakeEngine.new
end
end
class RequestWithoutFlashSupport < ActionDispatch::Request
undef_method :flash
end
def self.context(name, &block)
instance_eval(&block)
end
def call_failure(env_params = {})
env = {
'REQUEST_URI' => 'http://test.host/',
'HTTP_HOST' => 'test.host',
'REQUEST_METHOD' => 'GET',
'warden.options' => { scope: :user },
'action_dispatch.request.formats' => Array(env_params.delete('formats') || Mime[:html]),
'rack.input' => "",
'warden' => OpenStruct.new(message: nil)
}.merge!(env_params)
# Passing nil for action_dispatch.request.formats prevents the default from being used in Rails 5, need to remove it
if env.has_key?('action_dispatch.request.formats') && env['action_dispatch.request.formats'].nil?
env.delete 'action_dispatch.request.formats' unless env['action_dispatch.request.formats']
end
@response = (env.delete(:app) || Devise::FailureApp).call(env).to_a
@request = (env.delete(:request_klass) || ActionDispatch::Request).new(env)
end
context 'When redirecting' do
test 'returns to the default redirect location' do
call_failure
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://test.host/users/sign_in', @response.second['Location']
end
test 'returns to the default redirect location considering subdomain' do
call_failure('warden.options' => { scope: :subdomain_user })
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://sub.test.host/subdomain_users/sign_in', @response.second['Location']
end
test 'returns to the default redirect location for wildcard requests' do
call_failure 'action_dispatch.request.formats' => nil, 'HTTP_ACCEPT' => '*/*'
assert_equal 302, @response.first
assert_equal 'http://test.host/users/sign_in', @response.second['Location']
end
test 'returns to the root path if no session path is available' do
swap Devise, router_name: :fake_app do
call_failure app: RootFailureApp
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://test.host/', @response.second['Location']
end
end
test 'returns to the root path even when it\'s not defined' do
call_failure app: FailureWithoutRootPath
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://test.host/', @response.second['Location']
end
test 'returns to the root path considering subdomain if no session path is available' do
swap Devise, router_name: :fake_app do
call_failure app: FailureWithSubdomain
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://sub.test.host/', @response.second['Location']
end
end
test 'returns to the default redirect location considering the router for supplied scope' do
call_failure app: FakeEngineApp, 'warden.options' => { scope: :user_on_engine }
assert_equal 302, @response.first
assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
assert_equal 'http://test.host/user_on_engines/sign_in', @response.second['Location']
end
if Rails.application.config.respond_to?(:relative_url_root)
test 'returns to the default redirect location considering the relative url root' do
swap Rails.application.config, relative_url_root: "/sample" do
call_failure
assert_equal 302, @response.first
assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location']
end
end
test 'returns to the default redirect location considering the relative url root and subdomain' do
swap Rails.application.config, relative_url_root: "/sample" do
call_failure('warden.options' => { scope: :subdomain_user })
assert_equal 302, @response.first
assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location']
end
end
end
if Rails.application.config.action_controller.respond_to?(:relative_url_root)
test "returns to the default redirect location considering action_controller's relative url root" do
swap Rails.application.config.action_controller, relative_url_root: "/sample" do
call_failure
assert_equal 302, @response.first
assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location']
end
end
test "returns to the default redirect location considering action_controller's relative url root and subdomain" do
swap Rails.application.config.action_controller, relative_url_root: "/sample" do
call_failure('warden.options' => { scope: :subdomain_user })
assert_equal 302, @response.first
assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location']
end
end
end
test 'uses the proxy failure message as symbol' do
call_failure('warden' => OpenStruct.new(message: :invalid))
assert_equal 'Invalid email or password.', @request.flash[:alert]
assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
end
test 'supports authentication_keys as a Hash for the flash message' do
swap Devise, authentication_keys: { email: true, login: true } do
call_failure('warden' => OpenStruct.new(message: :invalid))
assert_equal 'Invalid email, login or password.', @request.flash[:alert]
end
end
test 'downcases authentication_keys for the flash message' do
call_failure('warden' => OpenStruct.new(message: :invalid))
assert_equal 'Invalid email or password.', @request.flash[:alert]
end
test 'humanizes the flash message' do
call_failure('warden' => OpenStruct.new(message: :invalid))
assert_equal @request.flash[:alert], @request.flash[:alert].humanize
end
test 'uses custom i18n options' do
call_failure('warden' => OpenStruct.new(message: :does_not_exist), app: FailureWithI18nOptions)
assert_equal 'User Steve does not exist', @request.flash[:alert]
end
test 'respects the i18n locale passed via warden options when redirecting' do
call_failure('warden' => OpenStruct.new(message: :invalid), 'warden.options' => { locale: :"pt-BR" })
assert_equal 'Email ou senha inválidos.', @request.flash[:alert]
assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
end
test 'uses the proxy failure message as string' do
call_failure('warden' => OpenStruct.new(message: 'Hello world'))
assert_equal 'Hello world', @request.flash[:alert]
assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
end
test 'set content type to default text/html' do
call_failure
assert_equal 'text/html; charset=utf-8', @response.second['Content-Type']
end
test 'set up a default message' do
call_failure
if Devise::Test.rails71_and_up?
assert_empty @response.last.body
else
assert_match(/You are being/, @response.last.body)
assert_match(/redirected/, @response.last.body)
assert_match(/users\/sign_in/, @response.last.body)
end
end
test 'works for any navigational format' do
swap Devise, navigational_formats: [:json] do
call_failure('formats' => Mime[:json])
assert_equal 302, @response.first
end
end
test 'redirects the correct format if it is a non-html format request' do
swap Devise, navigational_formats: [:js] do
call_failure('formats' => Mime[:js])
assert_equal 'http://test.host/users/sign_in.js', @response.second["Location"]
end
end
end
context 'For HTTP request' do
test 'return 401 status' do
call_failure('formats' => Mime[:json])
assert_equal 401, @response.first
end
test 'return appropriate body for xml' do
call_failure('formats' => Mime[:xml])
result = %(<?xml version="1.0" encoding="UTF-8"?>\n<errors>\n <error>You need to sign in or sign up before continuing.</error>\n</errors>\n)
assert_equal result, @response.last.body
end
test 'return appropriate body for json' do
call_failure('formats' => Mime[:json])
result = %({"error":"You need to sign in or sign up before continuing."})
assert_equal result, @response.last.body
end
test 'return 401 status for unknown formats' do
call_failure 'formats' => []
assert_equal 401, @response.first
end
test 'return WWW-authenticate headers if model allows' do
call_failure('formats' => Mime[:json])
assert_equal 'Basic realm="Application"', @response.second["WWW-Authenticate"]
end
test 'does not return WWW-authenticate headers if model does not allow' do
swap Devise, http_authenticatable: false do
call_failure('formats' => Mime[:json])
assert_nil @response.second["WWW-Authenticate"]
end
end
test 'works for any non navigational format' do
swap Devise, navigational_formats: [] do
call_failure('formats' => Mime[:html])
assert_equal 401, @response.first
end
end
test 'uses the failure message as response body' do
call_failure('formats' => Mime[:xml], 'warden' => OpenStruct.new(message: :invalid))
assert_match '<error>Invalid email or password.</error>', @response.third.body
end
test 'respects the i18n locale passed via warden options when responding to HTTP request' do
call_failure('formats' => Mime[:json], 'warden' => OpenStruct.new(message: :invalid), 'warden.options' => { locale: :"pt-BR" })
assert_equal %({"error":"Email ou senha inválidos."}), @response.third.body
end
context 'on ajax call' do
context 'when http_authenticatable_on_xhr is false' do
test 'dont return 401 with navigational formats' do
swap Devise, http_authenticatable_on_xhr: false do
call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
assert_equal 302, @response.first
assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
end
end
test 'dont return 401 with non navigational formats' do
swap Devise, http_authenticatable_on_xhr: false do
call_failure('formats' => Mime[:json], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
assert_equal 302, @response.first
assert_equal 'http://test.host/users/sign_in.json', @response.second["Location"]
end
end
end
context 'when http_authenticatable_on_xhr is true' do
test 'return 401' do
swap Devise, http_authenticatable_on_xhr: true do
call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
assert_equal 401, @response.first
end
end
test 'skip WWW-Authenticate header' do
swap Devise, http_authenticatable_on_xhr: true do
call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
assert_nil @response.second['WWW-Authenticate']
end
end
end
end
end
context 'With recall' do
test 'calls the original controller if invalid email or password' do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_includes @response.third.body, '<h2>Log in</h2>'
assert_includes @response.third.body, 'Invalid email or password.'
end
test 'calls the original controller if not confirmed email' do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :unconfirmed },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_includes @response.third.body, '<h2>Log in</h2>'
assert_includes @response.third.body, 'You have to confirm your email address before continuing.'
end
test 'calls the original controller if inactive account' do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :inactive },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_includes @response.third.body, '<h2>Log in</h2>'
assert_includes @response.third.body, 'Your account is not activated yet.'
end
if Rails.application.config.respond_to?(:relative_url_root)
test 'calls the original controller with the proper environment considering the relative url root' do
swap Rails.application.config, relative_url_root: "/sample" do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/sample/users/sign_in"},
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_includes @response.third.body, '<h2>Log in</h2>'
assert_includes @response.third.body, 'Invalid email or password.'
assert_equal '/sample', @request.env["SCRIPT_NAME"]
assert_equal '/users/sign_in', @request.env["PATH_INFO"]
end
end
end
test 'respects the i18n locale passed via warden options when recalling original controller' do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", locale: :"pt-BR" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_includes @response.third.body, '<h2>Log in</h2>'
assert_includes @response.third.body, 'Email ou senha inválidos.'
end
# TODO: remove conditional/else when supporting only responders 3.1+
if ActionController::Responder.respond_to?(:error_status=)
test 'respects the configured responder `error_status` for the status code' do
swap Devise.responder, error_status: :unprocessable_entity do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_equal 422, @response.first
assert_includes @response.third.body, 'Invalid email or password.'
end
end
test 'respects the configured responder `redirect_status` if the recall app returns a redirect status code' do
swap Devise.responder, redirect_status: :see_other do
env = {
"warden.options" => { recall: "devise/registrations#cancel", attempted_path: "/users/cancel" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_equal 303, @response.first
end
end
else
test 'uses default hardcoded responder `error_status` for the status code since responders version does not support configuring it' do
env = {
"warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_equal 200, @response.first
assert_includes @response.third.body, 'Invalid email or password.'
end
test 'users default hardcoded responder `redirect_status` for the status code since responders version does not support configuring it' do
env = {
"warden.options" => { recall: "devise/registrations#cancel", attempted_path: "/users/cancel" },
"devise.mapping" => Devise.mappings[:user],
"warden" => stub_everything
}
call_failure(env)
assert_equal 302, @response.first
end
end
end
context "Lazy loading" do
test "loads" do
assert_equal "yes it does", Devise::FailureApp.new.lazy_loading_works?
end
end
context "Without Flash Support" do
test "returns to the default redirect location without a flash message" do
call_failure request_klass: RequestWithoutFlashSupport
assert_equal 302, @response.first
assert_equal 'http://test.host/users/sign_in', @response.second['Location']
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/routes_test.rb | test/routes_test.rb | # frozen_string_literal: true
require 'test_helper'
ExpectedRoutingError = Minitest::Assertion
class DefaultRoutingTest < ActionController::TestCase
test 'map new user session' do
assert_recognizes({controller: 'devise/sessions', action: 'new'}, {path: 'users/sign_in', method: :get})
assert_named_route "/users/sign_in", :new_user_session_path
end
test 'map create user session' do
assert_recognizes({controller: 'devise/sessions', action: 'create'}, {path: 'users/sign_in', method: :post})
assert_named_route "/users/sign_in", :user_session_path
end
test 'map destroy user session' do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: 'users/sign_out', method: :delete})
assert_named_route "/users/sign_out", :destroy_user_session_path
end
test 'map new user confirmation' do
assert_recognizes({controller: 'devise/confirmations', action: 'new'}, 'users/confirmation/new')
assert_named_route "/users/confirmation/new", :new_user_confirmation_path
end
test 'map create user confirmation' do
assert_recognizes({controller: 'devise/confirmations', action: 'create'}, {path: 'users/confirmation', method: :post})
assert_named_route "/users/confirmation", :user_confirmation_path
end
test 'map show user confirmation' do
assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: 'users/confirmation', method: :get})
end
test 'map new user password' do
assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'users/password/new')
assert_named_route "/users/password/new", :new_user_password_path
end
test 'map create user password' do
assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: 'users/password', method: :post})
assert_named_route "/users/password", :user_password_path
end
test 'map edit user password' do
assert_recognizes({controller: 'devise/passwords', action: 'edit'}, 'users/password/edit')
assert_named_route "/users/password/edit", :edit_user_password_path
end
test 'map update user password' do
assert_recognizes({controller: 'devise/passwords', action: 'update'}, {path: 'users/password', method: :put})
end
test 'map new user unlock' do
assert_recognizes({controller: 'devise/unlocks', action: 'new'}, 'users/unlock/new')
assert_named_route "/users/unlock/new", :new_user_unlock_path
end
test 'map create user unlock' do
assert_recognizes({controller: 'devise/unlocks', action: 'create'}, {path: 'users/unlock', method: :post})
assert_named_route "/users/unlock", :user_unlock_path
end
test 'map show user unlock' do
assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: 'users/unlock', method: :get})
end
test 'map new user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, 'users/sign_up')
assert_named_route "/users/sign_up", :new_user_registration_path
end
test 'map create user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'create'}, {path: 'users', method: :post})
assert_named_route "/users", :user_registration_path
end
test 'map edit user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'edit'}, {path: 'users/edit', method: :get})
assert_named_route "/users/edit", :edit_user_registration_path
end
test 'map update user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'update'}, {path: 'users', method: :put})
end
test 'map destroy user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'destroy'}, {path: 'users', method: :delete})
end
test 'map cancel user registration' do
assert_recognizes({controller: 'devise/registrations', action: 'cancel'}, {path: 'users/cancel', method: :get})
assert_named_route "/users/cancel", :cancel_user_registration_path
end
test 'map omniauth callbacks' do
assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :get})
assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :post})
assert_named_route "/users/auth/facebook/callback", :user_facebook_omniauth_callback_path
# named open_id
assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :get})
assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :post})
assert_named_route "/users/auth/google/callback", :user_google_omniauth_callback_path
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'ysers/omniauth_callbacks', action: 'twitter'}, {path: 'users/auth/twitter/callback', method: :get})
end
end
protected
def assert_named_route(result, *args)
assert_equal result, @routes.url_helpers.send(*args)
end
end
class CustomizedRoutingTest < ActionController::TestCase
test 'map admin with :path option' do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'admin_area/sign_up', method: :get})
end
test 'map admin with :controllers option' do
assert_recognizes({controller: 'admins/sessions', action: 'new'}, {path: 'admin_area/sign_in', method: :get})
end
test 'does not map admin password' do
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'admin_area/password/new')
end
end
test 'subdomain admin' do
assert_recognizes({"host"=>"sub.example.com", controller: 'devise/sessions', action: 'new'}, {host: "sub.example.com", path: '/sub_admin/sign_in', method: :get})
end
test 'does only map reader password' do
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/sessions', action: 'new'}, 'reader/sessions/new')
end
assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'reader/password/new')
end
test 'map account with custom path name for session sign in' do
assert_recognizes({controller: 'devise/sessions', action: 'new', locale: 'en'}, '/en/accounts/login')
end
test 'map account with custom path name for session sign out' do
assert_recognizes({controller: 'devise/sessions', action: 'destroy', locale: 'en'}, {path: '/en/accounts/logout', method: :delete })
end
test 'map account with custom path name for password' do
assert_recognizes({controller: 'devise/passwords', action: 'new', locale: 'en'}, '/en/accounts/secret/new')
end
test 'map account with custom path name for registration' do
assert_recognizes({controller: 'devise/registrations', action: 'new', locale: 'en'}, '/en/accounts/management/register')
end
test 'map account with custom path name for edit registration' do
assert_recognizes({controller: 'devise/registrations', action: 'edit', locale: 'en'}, '/en/accounts/management/edit/profile')
end
test 'map account with custom path name for cancel registration' do
assert_recognizes({controller: 'devise/registrations', action: 'cancel', locale: 'en'}, '/en/accounts/management/giveup')
end
test 'map deletes with :sign_out_via option' do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :delete})
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :get})
end
end
test 'map posts with :sign_out_via option' do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :post})
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :get})
end
end
test 'map delete_or_posts with :sign_out_via option' do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :post})
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :delete})
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :get})
end
end
test 'map with constraints defined in hash' do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/headquarters/sign_up', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100/headquarters/sign_up', method: :get})
end
end
test 'map with constraints defined in block' do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/homebase/sign_up', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100//homebase/sign_up', method: :get})
end
end
test 'map with format false for sessions' do
expected_params = {controller: 'devise/sessions', action: 'new'}
assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in.json', method: :get})
end
end
test 'map with format false for passwords' do
expected_params = {controller: 'devise/passwords', action: 'create'}
assert_recognizes(expected_params, {path: '/htmlonly_admin/password', method: :post})
assert_raise ExpectedRoutingError do
assert_recognizes(expected_params, {path: '/htmlonly_admin/password.json', method: :post})
end
end
test 'map with format false for registrations' do
expected_params = {controller: 'devise/registrations', action: 'new'}
assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up.json', method: :get})
end
end
test 'map with format false for confirmations' do
expected_params = {controller: 'devise/confirmations', action: 'show'}
assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation.json', method: :get})
end
end
test 'map with format false for unlocks' do
expected_params = {controller: 'devise/unlocks', action: 'show'}
assert_recognizes(expected_params, {path: '/htmlonly_users/unlock', method: :get})
assert_raise ExpectedRoutingError do
assert_recognizes(expected_params, {path: '/htmlonly_users/unlock.json', method: :get})
end
end
test 'map with format false is not permanent' do
assert_equal "/set.json", @routes.url_helpers.set_path(:json)
end
test 'checks if mapping has proper configuration for omniauth callback' do
e = assert_raise ArgumentError do
routes = ActionDispatch::Routing::RouteSet.new
routes.draw do
devise_for :not_omniauthable, class_name: 'Admin', controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
end
end
assert_match "Mapping omniauth_callbacks on a resource that is not omniauthable", e.message
end
end
class ScopedRoutingTest < ActionController::TestCase
test 'map publisher account' do
assert_recognizes({controller: 'publisher/registrations', action: 'new'}, {path: '/publisher/accounts/sign_up', method: :get})
assert_equal '/publisher/accounts/sign_up', @routes.url_helpers.new_publisher_account_registration_path
end
test 'map publisher account merges path names' do
assert_recognizes({controller: 'publisher/sessions', action: 'new'}, {path: '/publisher/accounts/get_in', method: :get})
assert_equal '/publisher/accounts/get_in', @routes.url_helpers.new_publisher_account_session_path
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/devise_test.rb | test/devise_test.rb | # frozen_string_literal: true
require 'test_helper'
module Devise
def self.yield_and_restore
@@warden_configured = nil
c, b = @@warden_config, @@warden_config_blocks
yield
ensure
@@warden_config, @@warden_config_blocks = c, b
end
end
class DeviseTest < ActiveSupport::TestCase
test 'bcrypt on the class' do
password = "super secret"
klass = Struct.new(:pepper, :stretches).new("blahblah", 2)
hash = Devise::Encryptor.digest(klass, password)
assert_equal ::BCrypt::Password.create(hash), hash
klass = Struct.new(:pepper, :stretches).new("bla", 2)
hash = Devise::Encryptor.digest(klass, password)
assert_not_equal ::BCrypt::Password.new(hash), hash
end
test 'model options can be configured through Devise' do
swap Devise, allow_unconfirmed_access_for: 113, pepper: "foo" do
assert_equal 113, Devise.allow_unconfirmed_access_for
assert_equal "foo", Devise.pepper
end
end
test 'setup block yields self' do
Devise.setup do |config|
assert_equal Devise, config
end
end
test 'stores warden configuration' do
assert_kind_of Devise::Delegator, Devise.warden_config.failure_app
assert_equal :user, Devise.warden_config.default_scope
end
test 'warden manager user configuration through a block' do
Devise.yield_and_restore do
executed = false
Devise.warden do |config|
executed = true
assert_kind_of Warden::Config, config
end
Devise.configure_warden!
assert executed
end
end
test 'warden manager user configuration through multiple blocks' do
Devise.yield_and_restore do
executed = 0
3.times do
Devise.warden { |config| executed += 1 }
end
Devise.configure_warden!
assert_equal 3, executed
end
end
test 'add new module using the helper method' do
Devise.add_module(:coconut)
assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size
assert_not Devise::STRATEGIES.include?(:coconut)
assert_not defined?(Devise::Models::Coconut)
Devise::ALL.delete(:coconut)
Devise.add_module(:banana, strategy: :fruits)
assert_equal :fruits, Devise::STRATEGIES[:banana]
Devise::ALL.delete(:banana)
Devise::STRATEGIES.delete(:banana)
Devise.add_module(:kivi, controller: :fruits)
assert_equal :fruits, Devise::CONTROLLERS[:kivi]
Devise::ALL.delete(:kivi)
Devise::CONTROLLERS.delete(:kivi)
end
test 'Devise.secure_compare fails when comparing different strings or nil' do
[nil, ""].each do |empty|
assert_not Devise.secure_compare(empty, "something")
assert_not Devise.secure_compare("something", empty)
end
assert_not Devise.secure_compare(nil, nil)
assert_not Devise.secure_compare("size_1", "size_four")
end
test 'Devise.secure_compare passes when strings are the same, even two empty strings' do
assert Devise.secure_compare("", "")
assert Devise.secure_compare("something", "something")
end
test 'Devise.email_regexp should match valid email addresses' do
valid_emails = ["test@example.com", "jo@jo.co", "f4$_m@you.com", "testing.example@example.com.ua", "test@tt", "test@valid---domain.com"]
non_valid_emails = ["rex", "test user@example.com", "test_user@example server.com"]
valid_emails.each do |email|
assert_match Devise.email_regexp, email
end
non_valid_emails.each do |email|
assert_no_match Devise.email_regexp, email
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/test_models.rb | test/test_models.rb | # frozen_string_literal: true
class Configurable < User
devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable,
stretches: 15, pepper: 'abcdef', allow_unconfirmed_access_for: 5.days,
remember_for: 7.days, timeout_in: 15.minutes, unlock_in: 10.days
end
class WithValidation < Admin
devise :database_authenticatable, :validatable, password_length: 2..6
end
class UserWithValidation < User
validates_presence_of :username
end
class UserWithCustomHashing < User
protected
def password_digest(password)
password.reverse
end
end
class UserWithVirtualAttributes < User
devise case_insensitive_keys: [:email, :email_confirmation]
validates :email, presence: true, confirmation: { on: :create }
end
class Several < Admin
devise :validatable
devise :lockable
end
class Inheritable < Admin
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mapping_test.rb | test/mapping_test.rb | # frozen_string_literal: true
require 'test_helper'
class FakeRequest < Struct.new(:path_info, :params)
end
class MappingTest < ActiveSupport::TestCase
def fake_request(path, params = {})
FakeRequest.new(path, params)
end
test 'store options' do
mapping = Devise.mappings[:user]
assert_equal User, mapping.to
assert_equal User.devise_modules, mapping.modules
assert_equal "users", mapping.scoped_path
assert_equal :user, mapping.singular
assert_equal "users", mapping.path
assert_equal "/users", mapping.fullpath
end
test 'store options with namespace' do
mapping = Devise.mappings[:publisher_account]
assert_equal Admin, mapping.to
assert_equal "publisher/accounts", mapping.scoped_path
assert_equal :publisher_account, mapping.singular
assert_equal "accounts", mapping.path
assert_equal "/publisher/accounts", mapping.fullpath
end
test 'allows path to be given' do
assert_equal "admin_area", Devise.mappings[:admin].path
end
test 'allows to skip all routes' do
assert_equal [], Devise.mappings[:skip_admin].used_routes
end
test 'sign_out_via defaults to :delete' do
assert_equal :delete, Devise.mappings[:user].sign_out_via
end
test 'allows custom sign_out_via to be given' do
assert_equal :delete, Devise.mappings[:sign_out_via_delete].sign_out_via
assert_equal :post, Devise.mappings[:sign_out_via_post].sign_out_via
assert_equal [:delete, :post], Devise.mappings[:sign_out_via_delete_or_post].sign_out_via
end
test 'allows custom singular to be given' do
assert_equal "accounts", Devise.mappings[:manager].path
end
test 'has strategies depending on the model declaration' do
assert_equal [:rememberable, :database_authenticatable], Devise.mappings[:user].strategies
assert_equal [:database_authenticatable], Devise.mappings[:admin].strategies
end
test 'has no input strategies depending on the model declaration' do
assert_equal [:rememberable], Devise.mappings[:user].no_input_strategies
assert_equal [], Devise.mappings[:admin].no_input_strategies
end
test 'find scope for a given object' do
assert_equal :user, Devise::Mapping.find_scope!(User)
assert_equal :user, Devise::Mapping.find_scope!(:user)
assert_equal :user, Devise::Mapping.find_scope!("user")
assert_equal :user, Devise::Mapping.find_scope!(User.new)
end
test 'find scope works with single table inheritance' do
assert_equal :user, Devise::Mapping.find_scope!(Class.new(User))
assert_equal :user, Devise::Mapping.find_scope!(Class.new(User).new)
end
test 'find scope uses devise_scope' do
user = User.new
def user.devise_scope; :special_scope; end
assert_equal :special_scope, Devise::Mapping.find_scope!(user)
end
test 'find scope raises an error if cannot be found' do
assert_raise RuntimeError do
Devise::Mapping.find_scope!(String)
end
end
test 'return default path names' do
mapping = Devise.mappings[:user]
assert_equal 'sign_in', mapping.path_names[:sign_in]
assert_equal 'sign_out', mapping.path_names[:sign_out]
assert_equal 'password', mapping.path_names[:password]
assert_equal 'confirmation', mapping.path_names[:confirmation]
assert_equal 'sign_up', mapping.path_names[:sign_up]
assert_equal 'unlock', mapping.path_names[:unlock]
end
test 'allow custom path names to be given' do
mapping = Devise.mappings[:manager]
assert_equal 'login', mapping.path_names[:sign_in]
assert_equal 'logout', mapping.path_names[:sign_out]
assert_equal 'secret', mapping.path_names[:password]
assert_equal 'verification', mapping.path_names[:confirmation]
assert_equal 'register', mapping.path_names[:sign_up]
assert_equal 'unblock', mapping.path_names[:unlock]
end
test 'magic predicates' do
mapping = Devise.mappings[:user]
assert mapping.authenticatable?
assert mapping.confirmable?
assert mapping.recoverable?
assert mapping.rememberable?
assert mapping.registerable?
mapping = Devise.mappings[:admin]
assert mapping.authenticatable?
assert mapping.recoverable?
assert mapping.lockable?
assert_not mapping.omniauthable?
end
test 'find mapping by path' do
assert_raise RuntimeError do
Devise::Mapping.find_by_path!('/accounts/facebook/callback')
end
assert_nothing_raised do
Devise::Mapping.find_by_path!('/:locale/accounts/login')
end
assert_nothing_raised do
Devise::Mapping.find_by_path!('/accounts/facebook/callback', :path)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_test.rb | test/rails_test.rb | # frozen_string_literal: true
require 'test_helper'
class RailsTest < ActiveSupport::TestCase
test 'correct initializer position' do
initializer = Devise::Engine.initializers.detect { |i| i.name == 'devise.omniauth' }
assert_equal :load_config_initializers, initializer.after
assert_equal :build_middleware_stack, initializer.before
end
if Devise::Test.rails71_and_up?
test 'deprecator is added to application deprecators' do
assert_not_nil Rails.application.deprecators[:devise]
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
ENV["RAILS_ENV"] = "test"
DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
$:.unshift File.dirname(__FILE__)
puts "\n==> Devise.orm = #{DEVISE_ORM.inspect}"
require "rails_app/config/environment"
require "rails/test_help"
require "orm/#{DEVISE_ORM}"
I18n.load_path.concat Dir["#{File.dirname(__FILE__)}/support/locale/*.yml"]
require 'mocha/minitest'
require 'timecop'
require 'webrat'
Webrat.configure do |config|
config.mode = :rails
config.open_error_files = false
end
if ActiveSupport.respond_to?(:test_order)
ActiveSupport.test_order = :random
end
OmniAuth.config.logger = Logger.new('/dev/null')
# Add support to load paths so we can overwrite broken webrat setup
$:.unshift File.expand_path('../support', __FILE__)
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# For generators
require "rails/generators/test_case"
require "generators/devise/install_generator"
require "generators/devise/views_generator"
require "generators/devise/controllers_generator"
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/delegator_test.rb | test/delegator_test.rb | # frozen_string_literal: true
require 'test_helper'
class DelegatorTest < ActiveSupport::TestCase
def delegator
Devise::Delegator.new
end
test 'failure_app returns default failure app if no warden options in env' do
assert_equal Devise::FailureApp, delegator.failure_app({})
end
test 'failure_app returns default failure app if no scope in warden options' do
assert_equal Devise::FailureApp, delegator.failure_app({"warden.options" => {}})
end
test 'failure_app returns associated failure app by scope in the given environment' do
assert_kind_of Proc, delegator.failure_app({"warden.options" => {scope: "manager"}})
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models_test.rb | test/models_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'test_models'
class ActiveRecordTest < ActiveSupport::TestCase
def include_module?(klass, mod)
klass.devise_modules.include?(mod) &&
klass.included_modules.include?(Devise::Models::const_get(mod.to_s.classify))
end
def assert_include_modules(klass, *modules)
modules.each do |mod|
assert include_module?(klass, mod)
end
(Devise::ALL - modules).each do |mod|
assert_not include_module?(klass, mod)
end
end
test 'can cherry pick modules' do
assert_include_modules Admin, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable
end
test 'validations options are not applied too late' do
validators = WithValidation.validators_on :password
length = validators.find { |v| v.kind == :length }
assert_equal 2, length.options[:minimum].call
assert_equal 6, length.options[:maximum].call
end
test 'validations are applied just once' do
validators = Several.validators_on :password
assert_equal 1, validators.select{ |v| v.kind == :length }.length
end
test 'chosen modules are inheritable' do
assert_include_modules Inheritable, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable
end
test 'order of module inclusion' do
correct_module_order = [:database_authenticatable, :recoverable, :registerable, :confirmable, :lockable, :timeoutable]
incorrect_module_order = [:database_authenticatable, :timeoutable, :registerable, :recoverable, :lockable, :confirmable]
assert_include_modules Admin, *incorrect_module_order
# get module constants from symbol list
module_constants = correct_module_order.collect { |mod| Devise::Models::const_get(mod.to_s.classify) }
# confirm that they adhere to the order in ALL
# get included modules, filter out the noise, and reverse the order
assert_equal module_constants, (Admin.included_modules & module_constants).reverse
end
test 'raise error on invalid module' do
assert_raise NameError do
# Mix valid an invalid modules.
Configurable.class_eval { devise :database_authenticatable, :doesnotexit }
end
end
test 'set a default value for stretches' do
assert_equal 15, Configurable.stretches
end
test 'set a default value for pepper' do
assert_equal 'abcdef', Configurable.pepper
end
test 'set a default value for allow_unconfirmed_access_for' do
assert_equal 5.days, Configurable.allow_unconfirmed_access_for
end
test 'set a default value for remember_for' do
assert_equal 7.days, Configurable.remember_for
end
test 'set a default value for timeout_in' do
assert_equal 15.minutes, Configurable.timeout_in
end
test 'set a default value for unlock_in' do
assert_equal 10.days, Configurable.unlock_in
end
test 'set null fields on migrations' do
# Ignore email sending since no email exists.
klass = Class.new(Admin) do
def send_devise_notification(*); end
end
klass.create!
end
end
module StubModelFilters
def stub_filter(name)
define_singleton_method(name) { |*| nil }
end
end
class CheckFieldsTest < ActiveSupport::TestCase
test 'checks if the class respond_to the required fields' do
Player = Class.new do
extend Devise::Models
extend StubModelFilters
stub_filter :before_validation
stub_filter :after_update
devise :database_authenticatable
attr_accessor :encrypted_password, :email
end
assert_nothing_raised do
Devise::Models.check_fields!(Player)
end
end
test 'raises Devise::Models::MissingAtrribute and shows the missing attribute if the class doesn\'t respond_to one of the attributes' do
Clown = Class.new do
extend Devise::Models
extend StubModelFilters
stub_filter :before_validation
stub_filter :after_update
devise :database_authenticatable
attr_accessor :encrypted_password
end
assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: email" do
Devise::Models.check_fields!(Clown)
end
end
test 'raises Devise::Models::MissingAtrribute with all the missing attributes if there is more than one' do
Magician = Class.new do
extend Devise::Models
extend StubModelFilters
stub_filter :before_validation
stub_filter :after_update
devise :database_authenticatable
end
assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: encrypted_password, email" do
Devise::Models.check_fields!(Magician)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/parameter_sanitizer_test.rb | test/parameter_sanitizer_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'devise/parameter_sanitizer'
class ParameterSanitizerTest < ActiveSupport::TestCase
def sanitizer(params)
params = ActionController::Parameters.new(params)
Devise::ParameterSanitizer.new(User, :user, params)
end
test 'permits the default parameters for sign in' do
sanitizer = sanitizer('user' => { 'email' => 'jose' })
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({ 'email' => 'jose' }, sanitized)
end
test 'permits empty params when received not a hash' do
sanitizer = sanitizer({ 'user' => 'string' })
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({}, sanitized)
end
test 'does not rise error when received string instead of hash' do
sanitizer = sanitizer('user' => 'string')
assert_nothing_raised do
sanitizer.sanitize(:sign_in)
end
end
test 'does not rise error when received nil instead of hash' do
sanitizer = sanitizer('user' => nil)
assert_nothing_raised do
sanitizer.sanitize(:sign_in)
end
end
test 'permits empty params when received nil instead of hash' do
sanitizer = sanitizer({ 'user' => nil })
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({}, sanitized)
end
test 'permits the default parameters for sign up' do
sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' })
sanitized = sanitizer.sanitize(:sign_up)
assert_equal({ 'email' => 'jose' }, sanitized)
end
test 'permits the default parameters for account update' do
sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' })
sanitized = sanitizer.sanitize(:account_update)
assert_equal({ 'email' => 'jose' }, sanitized)
end
test 'permits news parameters for an existing action' do
sanitizer = sanitizer('user' => { 'username' => 'jose' })
sanitizer.permit(:sign_in, keys: [:username])
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({ 'username' => 'jose' }, sanitized)
end
test 'permits news parameters for an existing action with a block' do
sanitizer = sanitizer('user' => { 'username' => 'jose' })
sanitizer.permit(:sign_in) do |user|
user.permit(:username)
end
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({ 'username' => 'jose' }, sanitized)
end
test 'permit parameters for new actions' do
sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'name' => 'Jose' })
sanitizer.permit(:invite_user, keys: [:email, :name])
sanitized = sanitizer.sanitize(:invite_user)
assert_equal({ 'email' => 'jose@omglol', 'name' => 'Jose' }, sanitized)
end
test 'fails when we do not have any permitted parameters for the action' do
sanitizer = sanitizer('user' => { 'email' => 'jose', 'password' => 'invalid' })
assert_raise NotImplementedError do
sanitizer.sanitize(:unknown)
end
end
test 'removes permitted parameters' do
sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'username' => 'jose' })
sanitizer.permit(:sign_in, keys: [:username], except: [:email])
sanitized = sanitizer.sanitize(:sign_in)
assert_equal({ 'username' => 'jose' }, sanitized)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/assertions.rb | test/support/assertions.rb | # frozen_string_literal: true
require 'active_support/test_case'
class ActiveSupport::TestCase
def assert_blank(assertion)
assert assertion.blank?
end
def assert_present(assertion)
assert assertion.present?
end
def assert_email_sent(address = nil, &block)
assert_difference('ActionMailer::Base.deliveries.size', &block)
if address.present?
assert_equal address, ActionMailer::Base.deliveries.last['to'].to_s
end
end
def assert_email_not_sent(&block)
assert_no_difference('ActionMailer::Base.deliveries.size', &block)
end
def assert_raise_with_message(exception_klass, message, &block)
exception = assert_raise exception_klass, &block
assert_equal exception.message, message,
"The expected message was #{message} but your exception throwed #{exception.message}"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/http_method_compatibility.rb | test/support/http_method_compatibility.rb | # frozen_string_literal: true
module Devise
class IntegrationTest < ActionDispatch::IntegrationTest
end
class ControllerTestCase < ActionController::TestCase
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/helpers.rb | test/support/helpers.rb | # frozen_string_literal: true
require 'active_support/test_case'
class ActiveSupport::TestCase
def setup_mailer
ActionMailer::Base.deliveries = []
end
def store_translations(locale, translations, &block)
# Calling 'available_locales' before storing the translations to ensure
# that the I18n backend will be initialized before we store our custom
# translations, so they will always override the translations for the
# YML file.
I18n.available_locales
I18n.backend.store_translations(locale, translations)
yield
ensure
I18n.reload!
end
def generate_unique_email
@@email_count ||= 0
@@email_count += 1
"test#{@@email_count}@example.com"
end
def valid_attributes(attributes = {})
{ username: "usertest",
email: generate_unique_email,
password: '12345678',
password_confirmation: '12345678' }.update(attributes)
end
def new_user(attributes = {})
User.new(valid_attributes(attributes))
end
def create_user(attributes = {})
User.create!(valid_attributes(attributes))
end
def create_admin(attributes = {})
valid_attributes = valid_attributes(attributes)
valid_attributes.delete(:username)
Admin.create!(valid_attributes)
end
def create_user_without_email(attributes = {})
UserWithoutEmail.create!(valid_attributes(attributes))
end
def create_user_with_validations(attributes = {})
UserWithValidations.create!(valid_attributes(attributes))
end
# Execute the block setting the given values and restoring old values after
# the block is executed.
def swap(object, new_values)
old_values = {}
new_values.each do |key, value|
old_values[key] = object.send key
object.send :"#{key}=", value
end
clear_cached_variables(new_values)
yield
ensure
clear_cached_variables(new_values)
old_values.each do |key, value|
object.send :"#{key}=", value
end
end
def swap_model_config(model, new_values)
new_values.each do |key, value|
model.send :"#{key}=", value
end
yield
ensure
new_values.each_key do |key|
model.remove_instance_variable :"@#{key}"
end
end
def clear_cached_variables(options)
if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys)
Devise.mappings.each do |_, mapping|
mapping.to.instance_variable_set(:@devise_parameter_filter, nil)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/integration.rb | test/support/integration.rb | # frozen_string_literal: true
require 'action_dispatch/testing/integration'
class ActionDispatch::IntegrationTest
def warden
request.env['warden']
end
def create_user(options = {})
@user ||= begin
user = User.create!(
username: 'usertest',
email: options[:email] || 'user@test.com',
password: options[:password] || '12345678',
password_confirmation: options[:password] || '12345678',
created_at: Time.now.utc
)
user.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at]
user.confirm unless options[:confirm] == false
user.lock_access! if options[:locked] == true
User.validations_performed = false
user
end
end
def create_admin(options = {})
@admin ||= begin
admin = Admin.create!(
email: options[:email] || 'admin@test.com',
password: '123456', password_confirmation: '123456',
active: options[:active]
)
admin.confirm unless options[:confirm] == false
admin
end
end
def sign_in_as_user(options = {}, &block)
user = create_user(options)
visit_with_option options[:visit], new_user_session_path
fill_in 'email', with: options[:email] || 'user@test.com'
fill_in 'password', with: options[:password] || '12345678'
check 'remember me' if options[:remember_me] == true
yield if block_given?
click_button 'Log In'
user
end
def sign_in_as_admin(options = {}, &block)
admin = create_admin(options)
visit_with_option options[:visit], new_admin_session_path
fill_in 'email', with: 'admin@test.com'
fill_in 'password', with: '123456'
yield if block_given?
click_button 'Log In'
admin
end
# Fix assert_redirect_to in integration sessions because they don't take into
# account Middleware redirects.
#
def assert_redirected_to(url)
assert_includes [301, 302, 303], @integration_session.status,
"Expected status to be 301, 302, or 303, got #{@integration_session.status}"
assert_url url, @integration_session.headers["Location"]
end
def assert_current_url(expected)
assert_url expected, current_url
end
def assert_url(expected, actual)
assert_equal prepend_host(expected), prepend_host(actual)
end
protected
def visit_with_option(given, default)
case given
when String
visit given
when FalseClass
# Do nothing
else
visit default
end
end
def prepend_host(url)
url = "http://#{request.host}#{url}" if url[0] == ?/
url
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/webrat/matchers.rb | test/support/webrat/matchers.rb | # Monkey patch for Nokogiri changes - https://github.com/sparklemotion/nokogiri/issues/2469
module Webrat
module Matchers
class HaveSelector
def query
Nokogiri::CSS::Parser.new.parse(@expected.to_s).map do |ast|
if ::Gem::Version.new(Nokogiri::VERSION) < ::Gem::Version.new('1.17.2')
ast.to_xpath('//', Nokogiri::CSS::XPathVisitor.new)
else
ast.to_xpath(Nokogiri::CSS::XPathVisitor.new)
end
end.first
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/webrat/integrations/rails.rb | test/support/webrat/integrations/rails.rb | # frozen_string_literal: true
require 'webrat/core/elements/form'
require 'action_dispatch/testing/integration'
module Webrat
Form.class_eval do
def self.parse_rails_request_params(params)
Rack::Utils.parse_nested_query(params)
end
end
module Logging
# Avoid RAILS_DEFAULT_LOGGER deprecation warning
def logger # :nodoc:
::Rails.logger
end
end
class RailsAdapter
# This method is private within webrat gem and after Ruby 2.4 we get a lot of warnings because
# Webrat::Session#response is delegated to this method.
def response
integration_session.response
end
protected
def do_request(http_method, url, data, headers)
update_protocol(url)
integration_session.send(http_method, normalize_url(url), params: data, headers: headers)
end
end
end
module ActionDispatch #:nodoc:
IntegrationTest.class_eval do
include Webrat::Methods
include Webrat::Matchers
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/support/action_controller/record_identifier.rb | test/support/action_controller/record_identifier.rb | # frozen_string_literal: true
# Since webrat uses ActionController::RecordIdentifier class that was moved to
# ActionView namespace in Rails 4.1+
unless defined?(ActionController::RecordIdentifier)
require 'action_view/record_identifier'
module ActionController
RecordIdentifier = ActionView::RecordIdentifier
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/mounted_engine_test.rb | test/integration/mounted_engine_test.rb | # frozen_string_literal: true
require 'test_helper'
module MyMountableEngine
class Engine < ::Rails::Engine
isolate_namespace MyMountableEngine
end
class TestsController < ActionController::Base
def index
render plain: 'Root test successful'
end
def inner_route
render plain: 'Inner route test successful'
end
end
end
MyMountableEngine::Engine.routes.draw do
get 'test', to: 'tests#inner_route'
root to: 'tests#index'
end
# If disable_clear_and_finalize is set to true, Rails will not clear other routes when calling
# again the draw method. Look at the source code at:
# http://www.rubydoc.info/docs/rails/ActionDispatch/Routing/RouteSet:draw
Rails.application.routes.disable_clear_and_finalize = true
Rails.application.routes.draw do
authenticate(:user) do
mount MyMountableEngine::Engine, at: '/mountable_engine'
end
end
class AuthenticatedMountedEngineTest < Devise::IntegrationTest
test 'redirects to the sign in page when not authenticated' do
get '/mountable_engine'
follow_redirect!
assert_response :ok
assert_contain 'You need to sign in or sign up before continuing.'
end
test 'renders the mounted engine when authenticated' do
sign_in_as_user
get '/mountable_engine'
assert_response :success
assert_contain 'Root test successful'
end
test 'renders a inner route of the mounted engine when authenticated' do
sign_in_as_user
get '/mountable_engine/test'
assert_response :success
assert_contain 'Inner route test successful'
end
test 'respond properly to a non existing route of the mounted engine' do
sign_in_as_user
assert_raise ActionController::RoutingError do
get '/mountable_engine/non-existing-route'
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/trackable_test.rb | test/integration/trackable_test.rb | # frozen_string_literal: true
require 'test_helper'
class TrackableHooksTest < Devise::IntegrationTest
test "trackable should not run model validations" do
sign_in_as_user
assert_not User.validations_performed
end
test "current and last sign in timestamps are updated on each sign in" do
user = create_user
assert_nil user.current_sign_in_at
assert_nil user.last_sign_in_at
sign_in_as_user
user.reload
assert user.current_sign_in_at.acts_like?(:time)
assert user.last_sign_in_at.acts_like?(:time)
assert_equal user.current_sign_in_at, user.last_sign_in_at
assert user.current_sign_in_at >= user.created_at
delete destroy_user_session_path
new_time = 2.seconds.from_now
Time.stubs(:now).returns(new_time)
sign_in_as_user
user.reload
assert user.current_sign_in_at > user.last_sign_in_at
end
test "current and last sign in remote ip are updated on each sign in" do
user = create_user
assert_nil user.current_sign_in_ip
assert_nil user.last_sign_in_ip
sign_in_as_user
user.reload
assert_equal "127.0.0.1", user.current_sign_in_ip
assert_equal "127.0.0.1", user.last_sign_in_ip
end
test "current and last sign in remote ip returns original ip behind a non transparent proxy" do
user = create_user
arbitrary_ip = '200.121.1.69'
sign_in_as_user do
header 'HTTP_X_FORWARDED_FOR', arbitrary_ip
end
user.reload
assert_equal arbitrary_ip, user.current_sign_in_ip
assert_equal arbitrary_ip, user.last_sign_in_ip
end
test "increase sign in count" do
user = create_user
assert_equal 0, user.sign_in_count
sign_in_as_user
user.reload
assert_equal 1, user.sign_in_count
delete destroy_user_session_path
sign_in_as_user
user.reload
assert_equal 2, user.sign_in_count
end
test "does not update anything if user has signed out along the way" do
swap Devise, allow_unconfirmed_access_for: 0.days do
user = create_user(confirm: false)
sign_in_as_user
user.reload
assert_nil user.current_sign_in_at
assert_nil user.last_sign_in_at
end
end
test "do not track if devise.skip_trackable is set" do
user = create_user
sign_in_as_user do
header 'devise.skip_trackable', '1'
end
user.reload
assert_equal 0, user.sign_in_count
delete destroy_user_session_path
sign_in_as_user do
header 'devise.skip_trackable', false
end
user.reload
assert_equal 1, user.sign_in_count
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/database_authenticatable_test.rb | test/integration/database_authenticatable_test.rb | # frozen_string_literal: true
require 'test_helper'
class DatabaseAuthenticationTest < Devise::IntegrationTest
test 'sign in with email of different case should succeed when email is in the list of case insensitive keys' do
create_user(email: 'Foo@Bar.com')
sign_in_as_user do
fill_in 'email', with: 'foo@bar.com'
end
assert warden.authenticated?(:user)
end
test 'sign in with email of different case should fail when email is NOT the list of case insensitive keys' do
swap Devise, case_insensitive_keys: [] do
create_user(email: 'Foo@Bar.com')
sign_in_as_user do
fill_in 'email', with: 'foo@bar.com'
end
assert_not warden.authenticated?(:user)
end
end
test 'sign in with email including extra spaces should succeed when email is in the list of strip whitespace keys' do
create_user(email: ' foo@bar.com ')
sign_in_as_user do
fill_in 'email', with: 'foo@bar.com'
end
assert warden.authenticated?(:user)
end
test 'sign in with email including extra spaces should fail when email is NOT the list of strip whitespace keys' do
swap Devise, strip_whitespace_keys: [] do
create_user(email: 'foo@bar.com')
sign_in_as_user do
fill_in 'email', with: ' foo@bar.com '
end
assert_not warden.authenticated?(:user)
end
end
test 'sign in should not authenticate if not using proper authentication keys' do
swap Devise, authentication_keys: [:username] do
sign_in_as_user
assert_not warden.authenticated?(:user)
end
end
test 'sign in with invalid email should return to sign in form with error message' do
store_translations :en, devise: { failure: { admin: { not_found_in_database: 'Invalid email address' } } } do
sign_in_as_admin do
fill_in 'email', with: 'wrongemail@test.com'
end
assert_contain 'Invalid email address'
assert_not warden.authenticated?(:admin)
end
end
test 'sign in with invalid password should return to sign in form with error message' do
sign_in_as_admin do
fill_in 'password', with: 'abcdef'
end
assert_contain 'Invalid email or password'
assert_not warden.authenticated?(:admin)
end
test 'when in paranoid mode and without a valid e-mail' do
swap Devise, paranoid: true do
store_translations :en, devise: { failure: { not_found_in_database: 'Not found in database' } } do
sign_in_as_user do
fill_in 'email', with: 'wrongemail@test.com'
end
assert_not_contain 'Not found in database'
assert_contain 'Invalid email or password.'
end
end
end
test 'error message is configurable by resource name' do
store_translations :en, devise: { failure: { admin: { invalid: "Invalid credentials" } } } do
sign_in_as_admin do
fill_in 'password', with: 'abcdef'
end
assert_contain 'Invalid credentials'
end
end
test 'valid sign in calls after_database_authentication callback' do
user = create_user(email: ' foo@bar.com ')
User.expects(:find_for_database_authentication).returns user
user.expects :after_database_authentication
sign_in_as_user do
fill_in 'email', with: 'foo@bar.com'
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/timeoutable_test.rb | test/integration/timeoutable_test.rb | # frozen_string_literal: true
require 'test_helper'
class SessionTimeoutTest < Devise::IntegrationTest
def last_request_at
@controller.user_session['last_request_at']
end
test 'set last request at in user session after each request' do
sign_in_as_user
assert_not_nil last_request_at
@controller.user_session.delete('last_request_at')
get users_path
assert_not_nil last_request_at
end
test 'set last request at in user session after each request is skipped if tracking is disabled' do
sign_in_as_user
old_last_request = last_request_at
assert_not_nil last_request_at
get users_path, headers: { 'devise.skip_trackable' => true }
assert_equal old_last_request, last_request_at
end
test 'does not set last request at in user session after each request if timeoutable is disabled' do
sign_in_as_user
old_last_request = last_request_at
assert_not_nil last_request_at
new_time = 2.seconds.from_now
Time.stubs(:now).returns(new_time)
get users_path, headers: { 'devise.skip_timeoutable' => true }
assert_equal old_last_request, last_request_at
end
test 'does not time out user session before default limit time' do
sign_in_as_user
assert_response :success
assert warden.authenticated?(:user)
get users_path
assert_response :success
assert warden.authenticated?(:user)
end
test 'time out user session after default limit time when sign_out_all_scopes is false' do
swap Devise, sign_out_all_scopes: false do
sign_in_as_admin
user = sign_in_as_user
get expire_user_path(user)
assert_not_nil last_request_at
get users_path
assert_redirected_to users_path
assert_not warden.authenticated?(:user)
assert warden.authenticated?(:admin)
end
end
test 'time out all sessions after default limit time when sign_out_all_scopes is true' do
swap Devise, sign_out_all_scopes: true do
sign_in_as_admin
user = sign_in_as_user
get expire_user_path(user)
assert_not_nil last_request_at
get root_path
assert_not warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
end
end
test 'time out user session after default limit time and redirect to latest get request' do
user = sign_in_as_user
visit edit_form_user_path(user)
click_button 'Update'
sign_in_as_user
assert_equal edit_form_user_url(user), current_url
end
test 'time out is not triggered on sign out' do
user = sign_in_as_user
get expire_user_path(user)
delete destroy_user_session_path
assert_response :redirect
assert_redirected_to root_path
follow_redirect!
assert_contain 'Signed out successfully'
end
test 'expired session is not extended by sign in page' do
user = sign_in_as_user
get expire_user_path(user)
assert warden.authenticated?(:user)
get "/users/sign_in"
assert_redirected_to "/users/sign_in"
follow_redirect!
assert_response :success
assert_contain 'Log in'
assert_not warden.authenticated?(:user)
end
test 'time out is not triggered on sign in' do
user = sign_in_as_user
get expire_user_path(user)
post "/users/sign_in", params: { email: user.email, password: "123456" }
assert_response :redirect
follow_redirect!
assert_contain 'You are signed in'
end
test 'user configured timeout limit' do
swap Devise, timeout_in: 8.minutes do
user = sign_in_as_user
get users_path
assert_not_nil last_request_at
assert_response :success
assert warden.authenticated?(:user)
get expire_user_path(user)
get users_path
assert_redirected_to users_path
assert_not warden.authenticated?(:user)
end
end
test 'error message with i18n' do
store_translations :en, devise: {
failure: { user: { timeout: 'Session expired!' } }
} do
user = sign_in_as_user
get expire_user_path(user)
get root_path
follow_redirect!
assert_contain 'Session expired!'
end
end
test 'error message with i18n with double redirect' do
store_translations :en, devise: {
failure: { user: { timeout: 'Session expired!' } }
} do
user = sign_in_as_user
get expire_user_path(user)
get users_path
follow_redirect!
follow_redirect!
assert_contain 'Session expired!'
end
end
test 'error message redirect respects i18n locale set' do
user = sign_in_as_user
get expire_user_path(user)
get root_path(locale: "pt-BR")
follow_redirect!
assert_contain 'Sua sessão expirou. Por favor faça o login novamente para continuar.'
assert_not warden.authenticated?(:user)
end
test 'time out not triggered if remembered' do
user = sign_in_as_user remember_me: true
get expire_user_path(user)
assert_not_nil last_request_at
get users_path
assert_response :success
assert warden.authenticated?(:user)
end
test 'does not crash when the last_request_at is a String' do
user = sign_in_as_user
get edit_form_user_path(user, last_request_at: Time.now.utc.to_s)
get users_path
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/omniauthable_test.rb | test/integration/omniauthable_test.rb | # frozen_string_literal: true
require 'test_helper'
class OmniauthableIntegrationTest < Devise::IntegrationTest
FACEBOOK_INFO = {
"id" => '12345',
"link" => 'http://facebook.com/josevalim',
"email" => 'user@example.com',
"first_name" => 'Jose',
"last_name" => 'Valim',
"website" => 'http://blog.plataformatec.com.br'
}
setup do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = {
"uid" => '12345',
"provider" => 'facebook',
"user_info" => {"nickname" => 'josevalim'},
"credentials" => {"token" => 'plataformatec'},
"extra" => {"user_hash" => FACEBOOK_INFO}
}
OmniAuth.config.add_camelization 'facebook', 'FaceBook'
if OmniAuth.config.respond_to?(:request_validation_phase)
OmniAuth.config.request_validation_phase = ->(env) {}
end
end
teardown do
OmniAuth.config.camelizations.delete('facebook')
OmniAuth.config.test_mode = false
end
def stub_action!(name)
Users::OmniauthCallbacksController.class_eval do
alias_method :__old_facebook, :facebook
alias_method :facebook, name
end
yield
ensure
Users::OmniauthCallbacksController.class_eval do
alias_method :facebook, :__old_facebook
end
end
test "omniauth sign in should not run model validations" do
stub_action!(:sign_in_facebook) do
create_user
post "/users/auth/facebook"
follow_redirect!
assert warden.authenticated?(:user)
assert_not User.validations_performed
end
end
test "can access omniauth.auth in the env hash" do
post "/users/auth/facebook"
follow_redirect!
json = ActiveSupport::JSON.decode(response.body)
assert_equal "12345", json["uid"]
assert_equal "facebook", json["provider"]
assert_equal "josevalim", json["user_info"]["nickname"]
assert_equal FACEBOOK_INFO, json["extra"]["user_hash"]
assert_equal "plataformatec", json["credentials"]["token"]
end
test "cleans up session on sign up" do
assert_no_difference "User.count" do
post "/users/auth/facebook"
follow_redirect!
end
assert session["devise.facebook_data"]
assert_difference "User.count" do
visit "/users/sign_up"
fill_in "Password", with: "12345678"
fill_in "Password confirmation", with: "12345678"
click_button "Sign up"
end
assert_current_url "/"
assert_contain "You have signed up successfully."
assert_contain "Hello User user@example.com"
assert_not session["devise.facebook_data"]
end
test "cleans up session on cancel" do
assert_no_difference "User.count" do
post "/users/auth/facebook"
follow_redirect!
end
assert session["devise.facebook_data"]
visit "/users/cancel"
assert_not session["devise.facebook_data"]
end
test "cleans up session on sign in" do
assert_no_difference "User.count" do
post "/users/auth/facebook"
follow_redirect!
end
assert session["devise.facebook_data"]
sign_in_as_user
assert_not session["devise.facebook_data"]
end
test "sign in and send remember token if configured" do
post "/users/auth/facebook"
follow_redirect!
assert_nil warden.cookies["remember_user_token"]
stub_action!(:sign_in_facebook) do
create_user
post "/users/auth/facebook"
follow_redirect!
assert warden.authenticated?(:user)
assert warden.cookies["remember_user_token"]
end
end
test "authorization path via GET when Omniauth allowed_request_methods includes GET" do
original_allowed = OmniAuth.config.allowed_request_methods
OmniAuth.config.allowed_request_methods = [:get, :post]
get "/users/auth/facebook"
assert_response(:redirect)
ensure
OmniAuth.config.allowed_request_methods = original_allowed
end
test "authorization path via GET when Omniauth allowed_request_methods doesn't include GET" do
original_allowed = OmniAuth.config.allowed_request_methods
OmniAuth.config.allowed_request_methods = [:post]
assert_raises(ActionController::RoutingError) do
get "/users/auth/facebook"
end
ensure
OmniAuth.config.allowed_request_methods = original_allowed
end
test "generates a link to authenticate with provider" do
visit "/users/sign_in"
assert_select "form[action=?][method=post]", "/users/auth/facebook" do
assert_select "input[type=submit][value=?]", "Sign in with FaceBook"
end
end
test "generates a proper link when SCRIPT_NAME is set" do
header 'SCRIPT_NAME', '/q'
visit "/users/sign_in"
assert_select "form[action=?][method=post]", "/q/users/auth/facebook" do
assert_select "input[type=submit][value=?]", "Sign in with FaceBook"
end
end
test "handles callback error parameter according to the specification" do
OmniAuth.config.mock_auth[:facebook] = :access_denied
visit "/users/auth/facebook/callback?error=access_denied"
assert_current_url "/users/sign_in"
assert_contain 'Could not authenticate you from FaceBook because "Access denied".'
end
test "handles other exceptions from OmniAuth" do
OmniAuth.config.mock_auth[:facebook] = :invalid_credentials
post "/users/auth/facebook"
follow_redirect!
follow_redirect!
assert_contain 'Could not authenticate you from FaceBook because "Invalid credentials".'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/registerable_test.rb | test/integration/registerable_test.rb | # frozen_string_literal: true
require 'test_helper'
class RegistrationTest < Devise::IntegrationTest
test 'a guest admin should be able to sign in successfully' do
get new_admin_session_path
click_link 'Sign up'
assert_template 'registrations/new'
fill_in 'email', with: 'new_user@test.com'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user123'
click_button 'Sign up'
assert_contain 'You have signed up successfully'
assert warden.authenticated?(:admin)
assert_current_url "/admin_area/home"
admin = Admin.to_adapter.find_first(order: [:id, :desc])
assert_equal 'new_user@test.com', admin.email
end
test 'a guest admin should be able to sign in and be redirected to a custom location' do
Devise::RegistrationsController.any_instance.stubs(:after_sign_up_path_for).returns("/?custom=1")
get new_admin_session_path
click_link 'Sign up'
fill_in 'email', with: 'new_user@test.com'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user123'
click_button 'Sign up'
assert_contain 'Welcome! You have signed up successfully.'
assert warden.authenticated?(:admin)
assert_current_url "/?custom=1"
end
test 'a guest admin should not see a warning about minimum password length' do
get new_admin_session_path
assert_not_contain 'characters minimum'
end
def user_sign_up
ActionMailer::Base.deliveries.clear
get new_user_registration_path
fill_in 'email', with: 'new_user@test.com'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user123'
click_button 'Sign up'
end
test 'a guest user should see a warning about minimum password length' do
get new_user_registration_path
assert_contain '7 characters minimum'
end
test 'a guest user should be able to sign up successfully and be blocked by confirmation' do
user_sign_up
assert_contain 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
assert_not_contain 'You have to confirm your account before continuing'
assert_current_url "/"
assert_not warden.authenticated?(:user)
user = User.to_adapter.find_first(order: [:id, :desc])
assert_equal 'new_user@test.com', user.email
assert_not user.confirmed?
end
test 'a guest user should receive the confirmation instructions from the default mailer' do
user_sign_up
assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from
end
test 'a guest user should receive the confirmation instructions from a custom mailer' do
User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
user_sign_up
assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from
end
test 'a guest user should be blocked by confirmation and redirected to a custom path' do
Devise::RegistrationsController.any_instance.stubs(:after_inactive_sign_up_path_for).returns("/?custom=1")
get new_user_registration_path
fill_in 'email', with: 'new_user@test.com'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user123'
click_button 'Sign up'
assert_current_url "/?custom=1"
assert_not warden.authenticated?(:user)
end
test 'a guest user cannot sign up with invalid information' do
get new_user_registration_path
fill_in 'email', with: 'invalid_email'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user321'
click_button 'Sign up'
assert_template 'registrations/new'
assert_have_selector '#error_explanation'
assert_contain "Email is invalid"
assert_contain %r{Password confirmation doesn['’]t match Password}
assert_contain "2 errors prohibited"
assert_nil User.to_adapter.find_first
assert_not warden.authenticated?(:user)
end
test 'a guest should not sign up with email/password that already exists' do
create_user
get new_user_registration_path
fill_in 'email', with: 'user@test.com'
fill_in 'password', with: '123456'
fill_in 'password confirmation', with: '123456'
click_button 'Sign up'
assert_current_url '/users'
assert_contain(/Email.*already.*taken/)
assert_not warden.authenticated?(:user)
end
test 'a guest should not be able to change account' do
get edit_user_registration_path
assert_redirected_to new_user_session_path
follow_redirect!
assert_contain 'You need to sign in or sign up before continuing.'
end
test 'a signed in user should not be able to access sign up' do
sign_in_as_user
get new_user_registration_path
assert_redirected_to root_path
end
test 'a signed in user should be able to edit their account' do
sign_in_as_user
get edit_user_registration_path
fill_in 'email', with: 'user.new@example.com'
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_current_url '/'
assert_contain 'Your account has been updated successfully.'
assert_equal "user.new@example.com", User.to_adapter.find_first.email
end
test 'a signed in user should still be able to use the website after changing their password' do
sign_in_as_user
get edit_user_registration_path
fill_in 'password', with: '1234567890'
fill_in 'password confirmation', with: '1234567890'
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_contain 'Your account has been updated successfully.'
get users_path
assert warden.authenticated?(:user)
end
test 'a signed in user should not be able to use the website after changing their password if config.sign_in_after_change_password is false' do
swap Devise, sign_in_after_change_password: false do
sign_in_as_user
get edit_user_registration_path
fill_in 'password', with: '1234567890'
fill_in 'password confirmation', with: '1234567890'
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_contain 'Your account has been updated successfully, but since your password was changed, you need to sign in again.'
assert_equal new_user_session_path, @request.path
assert_not warden.authenticated?(:user)
end
end
test 'a signed in user should be able to use the website after changing its email with config.sign_in_after_change_password is false' do
swap Devise, sign_in_after_change_password: false do
sign_in_as_user
get edit_user_registration_path
fill_in 'email', with: 'user.new@example.com'
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_current_url '/'
assert_contain 'Your account has been updated successfully.'
assert warden.authenticated?(:user)
assert_equal "user.new@example.com", User.to_adapter.find_first.email
end
end
test 'a signed in user should not change their current user with invalid password' do
sign_in_as_user
get edit_user_registration_path
fill_in 'email', with: 'user.new@example.com'
fill_in 'current password', with: 'invalid'
click_button 'Update'
assert_template 'registrations/edit'
assert_contain 'user@test.com'
assert_have_selector 'form input[value="user.new@example.com"]'
assert_equal "user@test.com", User.to_adapter.find_first.email
end
test 'a signed in user should be able to edit their password' do
sign_in_as_user
get edit_user_registration_path
fill_in 'password', with: 'pass1234'
fill_in 'password confirmation', with: 'pass1234'
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_current_url '/'
assert_contain 'Your account has been updated successfully.'
assert User.to_adapter.find_first.valid_password?('pass1234')
end
test 'a signed in user should not be able to edit their password with invalid confirmation' do
sign_in_as_user
get edit_user_registration_path
fill_in 'password', with: 'pas123'
fill_in 'password confirmation', with: ''
fill_in 'current password', with: '12345678'
click_button 'Update'
assert_contain %r{Password confirmation doesn['’]t match Password}
assert_not User.to_adapter.find_first.valid_password?('pas123')
end
test 'a signed in user should see a warning about minimum password length' do
sign_in_as_user
get edit_user_registration_path
assert_contain 'characters minimum'
end
test 'a signed in user should be able to cancel their account' do
sign_in_as_user
get edit_user_registration_path
click_button "Cancel my account"
assert_contain "Bye! Your account has been successfully cancelled. We hope to see you again soon."
assert_empty User.to_adapter.find_all
end
test 'a user should be able to cancel sign up by deleting data in the session' do
get "/set"
assert_equal "something", @request.session["devise.foo_bar"]
get "/users/sign_up"
assert_equal "something", @request.session["devise.foo_bar"]
get "/users/cancel"
assert_nil @request.session["devise.foo_bar"]
assert_redirected_to new_user_registration_path
end
test 'a user with JSON sign up stub' do
get new_user_registration_path(format: 'json')
assert_response :success
assert_match %({"user":), response.body
assert_no_match(/"confirmation_token"/, response.body)
end
test 'an admin sign up with valid information in JSON format should return valid response' do
post admin_registration_path(format: 'json'), params: { admin: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } }
assert_response :success
assert_includes response.body, '{"admin":{'
admin = Admin.to_adapter.find_first(order: [:id, :desc])
assert_equal 'new_user@test.com', admin.email
end
test 'a user sign up with valid information in JSON format should return valid response' do
post user_registration_path(format: 'json'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } }
assert_response :success
assert_includes response.body, '{"user":{'
user = User.to_adapter.find_first(order: [:id, :desc])
assert_equal 'new_user@test.com', user.email
end
test 'a user sign up with invalid information in JSON format should return invalid response' do
post user_registration_path(format: 'json'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'invalid' } }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
end
test 'a user update information with valid data in JSON format should return valid response' do
user = sign_in_as_user
put user_registration_path(format: 'json'), params: { user: { current_password: '12345678', email: 'user.new@test.com' } }
assert_response :success
assert_equal 'user.new@test.com', user.reload.email
end
test 'a user update information with invalid data in JSON format should return invalid response' do
user = sign_in_as_user
put user_registration_path(format: 'json'), params: { user: { current_password: 'invalid', email: 'user.new@test.com' } }
assert_response :unprocessable_entity
assert_equal 'user@test.com', user.reload.email
end
test 'a user cancel their account in JSON format should return valid response' do
sign_in_as_user
delete user_registration_path(format: 'json')
assert_response :success
assert_equal 0, User.to_adapter.find_all.size
end
end
class ReconfirmableRegistrationTest < Devise::IntegrationTest
test 'a signed in admin should see a more appropriate flash message when editing their account if reconfirmable is enabled' do
sign_in_as_admin
get edit_admin_registration_path
fill_in 'email', with: 'admin.new@example.com'
fill_in 'current password', with: '123456'
click_button 'Update'
assert_current_url '/admin_area/home'
assert_contain 'but we need to verify your new email address'
assert_equal 'admin.new@example.com', Admin.to_adapter.find_first.unconfirmed_email
get edit_admin_registration_path
assert_contain 'Currently waiting confirmation for: admin.new@example.com'
end
test 'a signed in admin should not see a reconfirmation message if they did not change their password' do
sign_in_as_admin
get edit_admin_registration_path
fill_in 'password', with: 'pas123'
fill_in 'password confirmation', with: 'pas123'
fill_in 'current password', with: '123456'
click_button 'Update'
assert_current_url '/admin_area/home'
assert_contain 'Your account has been updated successfully.'
assert Admin.to_adapter.find_first.valid_password?('pas123')
end
test 'a signed in admin should not see a reconfirmation message if they did not change their email, despite having an unconfirmed email' do
sign_in_as_admin
get edit_admin_registration_path
fill_in 'email', with: 'admin.new@example.com'
fill_in 'current password', with: '123456'
click_button 'Update'
get edit_admin_registration_path
fill_in 'password', with: 'pas123'
fill_in 'password confirmation', with: 'pas123'
fill_in 'current password', with: '123456'
click_button 'Update'
assert_current_url '/admin_area/home'
assert_contain 'Your account has been updated successfully.'
assert_equal "admin.new@example.com", Admin.to_adapter.find_first.unconfirmed_email
assert Admin.to_adapter.find_first.valid_password?('pas123')
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/lockable_test.rb | test/integration/lockable_test.rb | # frozen_string_literal: true
require 'test_helper'
class LockTest < Devise::IntegrationTest
def visit_user_unlock_with_token(unlock_token)
visit user_unlock_path(unlock_token: unlock_token)
end
def send_unlock_request
user = create_user(locked: true)
ActionMailer::Base.deliveries.clear
visit new_user_session_path
click_link "Didn't receive unlock instructions?"
Devise.stubs(:friendly_token).returns("abcdef")
fill_in 'email', with: user.email
click_button 'Resend unlock instructions'
end
test 'user should be able to request a new unlock token' do
send_unlock_request
assert_template 'sessions/new'
assert_contain 'You will receive an email with instructions for how to unlock your account in a few minutes'
mail = ActionMailer::Base.deliveries.last
assert_equal 1, ActionMailer::Base.deliveries.size
assert_equal ['please-change-me@config-initializers-devise.com'], mail.from
assert_match user_unlock_path(unlock_token: 'abcdef'), mail.body.encoded
end
test 'user should receive the instructions from a custom mailer' do
User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
send_unlock_request
assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from
end
test 'unlocked user should not be able to request a unlock token' do
user = create_user(locked: false)
ActionMailer::Base.deliveries.clear
visit new_user_session_path
click_link "Didn't receive unlock instructions?"
fill_in 'email', with: user.email
click_button 'Resend unlock instructions'
assert_template 'unlocks/new'
assert_contain 'not locked'
assert_equal 0, ActionMailer::Base.deliveries.size
end
test 'unlocked pages should not be available if email strategy is disabled' do
visit "/admin_area/sign_in"
assert_raise Webrat::NotFoundError do
click_link "Didn't receive unlock instructions?"
end
assert_raise NameError do
visit new_admin_unlock_path
end
assert_raise ActionController::RoutingError do
visit "/admin_area/unlock/new"
end
end
test 'user with invalid unlock token should not be able to unlock an account' do
visit_user_unlock_with_token('invalid_token')
assert_response :success
assert_current_url '/users/unlock?unlock_token=invalid_token'
assert_have_selector '#error_explanation'
assert_contain %r{Unlock token(.*)invalid}
end
test "locked user should be able to unlock account" do
user = create_user
raw = user.lock_access!
visit_user_unlock_with_token(raw)
assert_current_url "/users/sign_in"
assert_contain 'Your account has been unlocked successfully. Please sign in to continue.'
assert_not user.reload.access_locked?
end
test "user should not send a new e-mail if already locked" do
user = create_user(locked: true)
user.failed_attempts = User.maximum_attempts + 1
user.save!
ActionMailer::Base.deliveries.clear
sign_in_as_user(password: "invalid")
assert_contain 'Your account is locked.'
assert_empty ActionMailer::Base.deliveries
end
test 'error message is configurable by resource name' do
store_translations :en, devise: {
failure: {user: {locked: "You are locked!"}}
} do
user = create_user(locked: true)
user.failed_attempts = User.maximum_attempts + 1
user.save!
sign_in_as_user(password: "invalid")
assert_contain "You are locked!"
end
end
test "user should not be able to sign in when locked" do
store_translations :en, devise: {
failure: {user: {locked: "You are locked!"}}
} do
user = create_user(locked: true)
user.failed_attempts = User.maximum_attempts + 1
user.save!
sign_in_as_user(password: "123456")
assert_contain "You are locked!"
end
end
test 'user should be able to request a new unlock token via JSON request and should return empty and valid response' do
user = create_user(locked: true)
ActionMailer::Base.deliveries.clear
post user_unlock_path(format: 'json'), params: { user: {email: user.email} }
assert_response :success
assert_equal({}.to_json, response.body)
assert_equal 1, ActionMailer::Base.deliveries.size
end
test 'unlocked user should not be able to request a unlock token via JSON request' do
user = create_user(locked: false)
ActionMailer::Base.deliveries.clear
post user_unlock_path(format: 'json'), params: { user: {email: user.email} }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
assert_equal 0, ActionMailer::Base.deliveries.size
end
test 'user with valid unlock token should be able to unlock account via JSON request' do
user = create_user()
raw = user.lock_access!
assert user.access_locked?
get user_unlock_path(format: 'json', unlock_token: raw)
assert_response :success
assert_includes response.body, '{"user":{'
end
test 'user with invalid unlock token should not be able to unlock the account via JSON request' do
get user_unlock_path(format: 'json', unlock_token: 'invalid_token')
assert_response :unprocessable_entity
assert_includes response.body, '{"unlock_token":['
end
test "in paranoid mode, when trying to unlock a user that exists it should not say that it exists if it is locked" do
swap Devise, paranoid: true do
user = create_user(locked: true)
visit new_user_session_path
click_link "Didn't receive unlock instructions?"
fill_in 'email', with: user.email
click_button 'Resend unlock instructions'
assert_current_url "/users/sign_in"
assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
end
end
test "in paranoid mode, when trying to unlock a user that exists it should not say that it exists if it is not locked" do
swap Devise, paranoid: true do
user = create_user(locked: false)
visit new_user_session_path
click_link "Didn't receive unlock instructions?"
fill_in 'email', with: user.email
click_button 'Resend unlock instructions'
assert_current_url "/users/sign_in"
assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
end
end
test "in paranoid mode, when trying to unlock a user that does not exists it should not say that it does not exists" do
swap Devise, paranoid: true do
visit new_user_session_path
click_link "Didn't receive unlock instructions?"
fill_in 'email', with: "arandomemail@hotmail.com"
click_button 'Resend unlock instructions'
assert_not_contain "1 error prohibited this user from being saved:"
assert_not_contain "Email not found"
assert_current_url "/users/sign_in"
assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
end
end
test "in paranoid mode, when locking a user that exists it should not say that the user was locked" do
swap Devise, paranoid: true, maximum_attempts: 1 do
user = create_user(locked: false)
visit new_user_session_path
fill_in 'email', with: user.email
fill_in 'password', with: "abadpassword"
click_button 'Log in'
fill_in 'email', with: user.email
fill_in 'password', with: "abadpassword"
click_button 'Log in'
assert_current_url "/users/sign_in"
assert_not_contain "locked"
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/rememberable_test.rb | test/integration/rememberable_test.rb | # frozen_string_literal: true
require 'test_helper'
class RememberMeTest < Devise::IntegrationTest
def create_user_and_remember(add_to_token = '')
user = create_user
user.remember_me!
raw_cookie = User.serialize_into_cookie(user).tap { |a| a[1] << add_to_token }
cookies['remember_user_token'] = generate_signed_cookie(raw_cookie)
user
end
def generate_signed_cookie(raw_cookie)
request = ActionController::TestRequest.create(Class.new) # needs a "controller class"
request.cookie_jar.signed['raw_cookie'] = raw_cookie
request.cookie_jar['raw_cookie']
end
def signed_cookie(key)
controller.send(:cookies).signed[key]
end
def cookie_expires(key)
cookie = response.headers["Set-Cookie"].split("\n").grep(/^#{key}/).first
expires = cookie.split(";").map(&:strip).grep(/^expires=/).first
Time.parse(expires).utc
end
test 'do not remember the user if they have not checked remember me option' do
sign_in_as_user
assert_nil request.cookies["remember_user_cookie"]
end
test 'handle unverified requests gets rid of caches' do
swap ApplicationController, allow_forgery_protection: true do
post exhibit_user_url(1)
assert_not warden.authenticated?(:user)
create_user_and_remember
post exhibit_user_url(1)
assert_equal "User is not authenticated", response.body
assert_not warden.authenticated?(:user)
end
end
test 'handle unverified requests does not create cookies on sign in' do
swap ApplicationController, allow_forgery_protection: true do
get new_user_session_path
assert request.session[:_csrf_token]
post user_session_path, params: {
authenticity_token: "oops",
user: { email: "jose.valim@gmail.com", password: "123456", remember_me: "1" }
}
assert_not warden.authenticated?(:user)
assert_not request.cookies['remember_user_token']
end
end
test 'generate remember token after sign in' do
sign_in_as_user remember_me: true
assert request.cookies['remember_user_token']
end
test 'generate remember token after sign in setting cookie options' do
# We test this by asserting the cookie is not sent after the redirect
# since we changed the domain. This is the only difference with the
# previous test.
swap Devise, rememberable_options: { domain: "omg.somewhere.com" } do
sign_in_as_user remember_me: true
assert_nil request.cookies["remember_user_token"]
end
end
test 'generate remember token with a custom key' do
swap Devise, rememberable_options: { key: "v1lat_token" } do
sign_in_as_user remember_me: true
assert request.cookies["v1lat_token"]
end
end
test 'generate remember token after sign in setting session options' do
begin
Rails.configuration.session_options[:domain] = "omg.somewhere.com"
sign_in_as_user remember_me: true
assert_nil request.cookies["remember_user_token"]
ensure
Rails.configuration.session_options.delete(:domain)
end
end
test 'remember the user before sign in' do
user = create_user_and_remember
get users_path
assert_response :success
assert warden.authenticated?(:user)
assert warden.user(:user) == user
end
test 'remember the user before sign up and redirect them to their home' do
create_user_and_remember
get new_user_registration_path
assert warden.authenticated?(:user)
assert_redirected_to root_path
end
test 'does not extend remember period through sign in' do
swap Devise, extend_remember_period: true, remember_for: 1.year do
user = create_user
user.remember_me!
user.remember_created_at = old = 10.days.ago
user.save
sign_in_as_user remember_me: true
user.reload
assert warden.user(:user) == user
assert_equal old.to_i, user.remember_created_at.to_i
end
end
test 'extends remember period when extend remember period config is true' do
swap Devise, extend_remember_period: true, remember_for: 1.year do
create_user_and_remember
old_remember_token = nil
travel_to 1.day.ago do
get root_path
old_remember_token = request.cookies['remember_user_token']
end
get root_path
current_remember_token = request.cookies['remember_user_token']
assert_not_equal old_remember_token, current_remember_token
end
end
test 'does not extend remember period when extend period config is false' do
swap Devise, extend_remember_period: false, remember_for: 1.year do
create_user_and_remember
old_remember_token = nil
travel_to 1.day.ago do
get root_path
old_remember_token = request.cookies['remember_user_token']
end
get root_path
current_remember_token = request.cookies['remember_user_token']
assert_equal old_remember_token, current_remember_token
end
end
test 'do not remember other scopes' do
create_user_and_remember
get root_path
assert_response :success
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
end
test 'do not remember with invalid token' do
create_user_and_remember('add')
get users_path
assert_not warden.authenticated?(:user)
assert_redirected_to new_user_session_path
end
test 'do not remember with expired token' do
create_user_and_remember
swap Devise, remember_for: 0.days do
get users_path
assert_not warden.authenticated?(:user)
assert_redirected_to new_user_session_path
end
end
test 'do not remember the user anymore after forget' do
create_user_and_remember
get users_path
assert warden.authenticated?(:user)
delete destroy_user_session_path
assert_not warden.authenticated?(:user)
assert_nil warden.cookies['remember_user_token']
get users_path
assert_not warden.authenticated?(:user)
end
test 'changing user password expires remember me token' do
user = create_user_and_remember
user.password = "another_password"
user.password_confirmation = "another_password"
user.save!
get users_path
assert_not warden.authenticated?(:user)
end
test 'valid sign in calls after_remembered callback' do
user = create_user_and_remember
User.expects(:serialize_from_cookie).returns user
user.expects :after_remembered
get new_user_registration_path
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/http_authenticatable_test.rb | test/integration/http_authenticatable_test.rb | # frozen_string_literal: true
require 'test_helper'
class HttpAuthenticationTest < Devise::IntegrationTest
test 'sign in with HTTP should not run model validations' do
sign_in_as_new_user_with_http
assert_not User.validations_performed
end
test 'handles unverified requests gets rid of caches but continues signed in' do
swap ApplicationController, allow_forgery_protection: true do
create_user
post exhibit_user_url(1), headers: { "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("user@test.com:12345678")}" }
assert warden.authenticated?(:user)
assert_equal "User is authenticated", response.body
end
end
test 'sign in should authenticate with http' do
swap Devise, skip_session_storage: [] do
sign_in_as_new_user_with_http
assert_response 200
assert_match '"email":"user@test.com"', response.body
assert warden.authenticated?(:user)
get users_path(format: :json)
assert_response 200
end
end
test 'sign in should authenticate with http but not emit a cookie if skipping session storage' do
swap Devise, skip_session_storage: [:http_auth] do
sign_in_as_new_user_with_http
assert_response 200
assert_match '"email":"user@test.com"', response.body
assert warden.authenticated?(:user)
get users_path(format: :json)
assert_response 401
end
end
test 'returns a custom response with www-authenticate header on failures' do
sign_in_as_new_user_with_http("unknown")
assert_equal 401, status
assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"]
end
test 'uses the request format as response content type' do
sign_in_as_new_user_with_http("unknown")
assert_equal 401, status
assert_equal "application/json; charset=utf-8", headers["Content-Type"]
assert_match '"error":"Invalid email or password."', response.body
end
test 'returns a custom response with www-authenticate and chosen realm' do
swap Devise, http_authentication_realm: "MyApp" do
sign_in_as_new_user_with_http("unknown")
assert_equal 401, status
assert_equal 'Basic realm="MyApp"', headers["WWW-Authenticate"]
end
end
test 'sign in should authenticate with http even with specific authentication keys' do
swap Devise, authentication_keys: [:username] do
sign_in_as_new_user_with_http("usertest")
assert_response :success
assert_match '"email":"user@test.com"', response.body
assert warden.authenticated?(:user)
end
end
test 'it uses appropriate authentication_keys when configured with hash' do
swap Devise, authentication_keys: { username: false, email: false } do
sign_in_as_new_user_with_http("usertest")
assert_response :success
assert_match '"email":"user@test.com"', response.body
assert warden.authenticated?(:user)
end
end
test 'it uses the appropriate key when configured explicitly' do
swap Devise, authentication_keys: { email: false, username: false }, http_authentication_key: :username do
sign_in_as_new_user_with_http("usertest")
assert_response :success
assert_match '"email":"user@test.com"', response.body
assert warden.authenticated?(:user)
end
end
test 'test request with oauth2 header doesnt get mistaken for basic authentication' do
swap Devise, http_authenticatable: true do
add_oauth2_header
assert_equal 401, status
assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"]
end
end
private
def sign_in_as_new_user_with_http(username = "user@test.com", password = "12345678")
user = create_user
get users_path(format: :json), headers: { "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{username}:#{password}")}" }
user
end
# Sign in with oauth2 token. This is just to test that it isn't misinterpreted as basic authentication
def add_oauth2_header
user = create_user
get users_path(format: :json), headers: { "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}" }
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/authenticatable_test.rb | test/integration/authenticatable_test.rb | # frozen_string_literal: true
require 'test_helper'
class AuthenticationSanityTest < Devise::IntegrationTest
test 'sign in should not run model validations' do
sign_in_as_user
assert_not User.validations_performed
end
test 'home should be accessible without sign in' do
visit '/'
assert_response :success
assert_template 'home/index'
end
test 'sign in as user should not authenticate admin scope' do
sign_in_as_user
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
end
test 'sign in as admin should not authenticate user scope' do
sign_in_as_admin
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
end
test 'sign in as both user and admin at same time' do
sign_in_as_user
sign_in_as_admin
assert warden.authenticated?(:user)
assert warden.authenticated?(:admin)
end
test 'sign out as user should not touch admin authentication if sign_out_all_scopes is false' do
swap Devise, sign_out_all_scopes: false do
sign_in_as_user
sign_in_as_admin
delete destroy_user_session_path
assert_not warden.authenticated?(:user)
assert warden.authenticated?(:admin)
end
end
test 'sign out as admin should not touch user authentication if sign_out_all_scopes is false' do
swap Devise, sign_out_all_scopes: false do
sign_in_as_user
sign_in_as_admin
delete destroy_admin_session_path
assert_not warden.authenticated?(:admin)
assert warden.authenticated?(:user)
end
end
test 'sign out as user should also sign out admin if sign_out_all_scopes is true' do
swap Devise, sign_out_all_scopes: true do
sign_in_as_user
sign_in_as_admin
delete destroy_user_session_path
assert_not warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
end
end
test 'sign out as admin should also sign out user if sign_out_all_scopes is true' do
swap Devise, sign_out_all_scopes: true do
sign_in_as_user
sign_in_as_admin
delete destroy_admin_session_path
assert_not warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
end
end
test 'not signed in as admin should not be able to access admins actions' do
get admins_path
assert_redirected_to new_admin_session_path
assert_not warden.authenticated?(:admin)
end
test 'signed in as user should not be able to access admins actions' do
sign_in_as_user
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
get admins_path
assert_redirected_to new_admin_session_path
end
test 'signed in as admin should be able to access admin actions' do
sign_in_as_admin
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
get admins_path
assert_response :success
assert_template 'admins/index'
assert_contain 'Welcome Admin'
end
test 'authenticated admin should not be able to sign as admin again' do
sign_in_as_admin
get new_admin_session_path
assert_response :redirect
assert_redirected_to admin_root_path
assert warden.authenticated?(:admin)
end
test 'authenticated admin should be able to sign out' do
sign_in_as_admin
assert warden.authenticated?(:admin)
delete destroy_admin_session_path
assert_response :redirect
assert_redirected_to root_path
get root_path
assert_contain 'Signed out successfully'
assert_not warden.authenticated?(:admin)
end
test 'unauthenticated admin set message on sign out' do
delete destroy_admin_session_path
assert_response :redirect
assert_redirected_to root_path
get root_path
assert_contain 'Signed out successfully'
end
test 'scope uses custom failure app' do
put "/en/accounts/management"
assert_equal "Oops, not found", response.body
assert_equal 404, response.status
end
end
class AuthenticationRoutesRestrictions < Devise::IntegrationTest
test 'not signed in should not be able to access private route (authenticate denied)' do
get private_path
assert_redirected_to new_admin_session_path
assert_not warden.authenticated?(:admin)
end
test 'signed in as user should not be able to access private route restricted to admins (authenticate denied)' do
sign_in_as_user
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
get private_path
assert_redirected_to new_admin_session_path
end
test 'signed in as admin should be able to access private route restricted to admins (authenticate accepted)' do
sign_in_as_admin
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
get private_path
assert_response :success
assert_template 'home/private'
assert_contain 'Private!'
end
test 'signed in as inactive admin should not be able to access private/active route restricted to active admins (authenticate denied)' do
sign_in_as_admin(active: false)
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
assert_raises ActionController::RoutingError do
get "/private/active"
end
end
test 'signed in as active admin should be able to access private/active route restricted to active admins (authenticate accepted)' do
sign_in_as_admin(active: true)
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
get private_active_path
assert_response :success
assert_template 'home/private'
assert_contain 'Private!'
end
test 'signed in as admin should get admin dashboard (authenticated accepted)' do
sign_in_as_admin
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
get dashboard_path
assert_response :success
assert_template 'home/admin_dashboard'
assert_contain 'Admin dashboard'
end
test 'signed in as user should get user dashboard (authenticated accepted)' do
sign_in_as_user
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
get dashboard_path
assert_response :success
assert_template 'home/user_dashboard'
assert_contain 'User dashboard'
end
test 'not signed in should get no dashboard (authenticated denied)' do
assert_raises ActionController::RoutingError do
get dashboard_path
end
end
test 'signed in as inactive admin should not be able to access dashboard/active route restricted to active admins (authenticated denied)' do
sign_in_as_admin(active: false)
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
assert_raises ActionController::RoutingError do
get "/dashboard/active"
end
end
test 'signed in as active admin should be able to access dashboard/active route restricted to active admins (authenticated accepted)' do
sign_in_as_admin(active: true)
assert warden.authenticated?(:admin)
assert_not warden.authenticated?(:user)
get dashboard_active_path
assert_response :success
assert_template 'home/admin_dashboard'
assert_contain 'Admin dashboard'
end
test 'signed in user should not see unauthenticated page (unauthenticated denied)' do
sign_in_as_user
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
assert_raises ActionController::RoutingError do
get join_path
end
end
test 'not signed in users should see unauthenticated page (unauthenticated accepted)' do
get join_path
assert_response :success
assert_template 'home/join'
assert_contain 'Join'
end
end
class AuthenticationRedirectTest < Devise::IntegrationTest
test 'redirect from warden shows sign in or sign up message' do
get admins_path
warden_path = new_admin_session_path
assert_redirected_to warden_path
get warden_path
assert_contain 'You need to sign in or sign up before continuing.'
end
test 'redirect from warden respects i18n locale set at the controller' do
get admins_path(locale: "pt-BR")
assert_redirected_to new_admin_session_path
follow_redirect!
assert_contain 'Para continuar, faça login ou registre-se.'
end
test 'redirect to default url if no other was configured' do
sign_in_as_user
assert_template 'home/index'
assert_nil session[:"user_return_to"]
end
test 'redirect to requested url after sign in' do
get users_path
assert_redirected_to new_user_session_path
assert_equal users_path, session[:"user_return_to"]
follow_redirect!
sign_in_as_user visit: false
assert_current_url '/users'
assert_nil session[:"user_return_to"]
end
test 'redirect to last requested url overwriting the stored return_to option' do
get expire_user_path(create_user)
assert_redirected_to new_user_session_path
assert_equal expire_user_path(create_user), session[:"user_return_to"]
get users_path
assert_redirected_to new_user_session_path
assert_equal users_path, session[:"user_return_to"]
follow_redirect!
sign_in_as_user visit: false
assert_current_url '/users'
assert_nil session[:"user_return_to"]
end
test 'xml http requests does not store urls for redirect' do
get users_path, headers: { 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' }
assert_equal 401, response.status
assert_nil session[:"user_return_to"]
end
test 'redirect to configured home path for a given scope after sign in' do
sign_in_as_admin
assert_equal "/admin_area/home", @request.path
end
test 'require_no_authentication should set the already_authenticated flash message' do
sign_in_as_user
visit new_user_session_path
assert_equal I18n.t("devise.failure.already_authenticated"), flash[:alert]
end
test 'require_no_authentication should set the already_authenticated flash message as admin' do
store_translations :en, devise: { failure: { admin: { already_authenticated: 'You are already signed in as admin.' } } } do
sign_in_as_admin
visit new_admin_session_path
assert_equal "You are already signed in as admin.", flash[:alert]
end
end
end
class AuthenticationSessionTest < Devise::IntegrationTest
test 'destroyed account is signed out' do
sign_in_as_user
get '/users'
User.destroy_all
get '/users'
assert_redirected_to new_user_session_path
end
test 'refreshes _csrf_token' do
swap ApplicationController, allow_forgery_protection: true do
get new_user_session_path
token_from_session = request.session[:_csrf_token]
if Devise::Test.rails71_and_up?
token_from_env = request.env["action_controller.csrf_token"]
end
sign_in_as_user
assert_not_equal request.session[:_csrf_token], token_from_session
if Devise::Test.rails71_and_up?
assert_not_equal request.env["action_controller.csrf_token"], token_from_env
end
end
end
test 'allows session to be set for a given scope' do
sign_in_as_user
get '/users'
assert_equal "Cart", @controller.user_session[:cart]
end
test 'session id is changed on sign in' do
get '/users'
session_id = request.session["session_id"]
get '/users'
assert_equal session_id, request.session["session_id"]
sign_in_as_user
assert_not_equal session_id, request.session["session_id"]
end
end
class AuthenticationWithScopedViewsTest < Devise::IntegrationTest
test 'renders the scoped view if turned on and view is available' do
swap Devise, scoped_views: true do
assert_raise Webrat::NotFoundError do
sign_in_as_user
end
assert_match %r{Special user view}, response.body
end
end
test 'renders the scoped view if turned on in a specific controller' do
begin
Devise::SessionsController.scoped_views = true
assert_raise Webrat::NotFoundError do
sign_in_as_user
end
assert_match %r{Special user view}, response.body
assert_not Devise::PasswordsController.scoped_views?
ensure
Devise::SessionsController.send :remove_instance_variable, :@scoped_views
end
end
test 'does not render the scoped view if turned off' do
swap Devise, scoped_views: false do
assert_nothing_raised do
sign_in_as_user
end
end
end
test 'does not render the scoped view if not available' do
swap Devise, scoped_views: true do
assert_nothing_raised do
sign_in_as_admin
end
end
end
end
class AuthenticationOthersTest < Devise::IntegrationTest
test 'handles unverified requests gets rid of caches' do
swap ApplicationController, allow_forgery_protection: true do
post exhibit_user_url(1)
assert_not warden.authenticated?(:user)
sign_in_as_user
assert warden.authenticated?(:user)
post exhibit_user_url(1)
assert_not warden.authenticated?(:user)
assert_equal "User is not authenticated", response.body
end
end
test 'uses the custom controller with the custom controller view' do
get '/admin_area/sign_in'
assert_contain 'Log in'
assert_contain 'Welcome to "admins/sessions" controller!'
assert_contain 'Welcome to "sessions/new" view!'
end
test 'render 404 on roles without routes' do
assert_raise ActionController::RoutingError do
get '/admin_area/password/new'
end
end
test 'does not intercept Rails 401 responses' do
get '/unauthenticated'
assert_equal 401, response.status
end
test 'render 404 on roles without mapping' do
assert_raise AbstractController::ActionNotFound do
get '/sign_in'
end
end
test 'sign in with script name' do
assert_nothing_raised do
get new_user_session_path, headers: { "SCRIPT_NAME" => "/omg" }
fill_in "email", with: "user@test.com"
end
end
test 'sign in stub in json format' do
get new_user_session_path(format: 'json')
assert_match '{"user":{', response.body
assert_match '"email":""', response.body
assert_match '"password":null', response.body
end
test 'sign in stub in json with non attribute key' do
swap Devise, authentication_keys: [:other_key] do
get new_user_session_path(format: 'json')
assert_match '{"user":{', response.body
assert_match '"other_key":null', response.body
assert_match '"password":null', response.body
end
end
test 'uses the mapping from router' do
sign_in_as_user visit: "/as/sign_in"
assert warden.authenticated?(:user)
assert_not warden.authenticated?(:admin)
end
test 'sign in with json format returns json response' do
create_user
post user_session_path(format: 'json'), params: { user: {email: "user@test.com", password: '12345678'} }
assert_response :success
assert_includes response.body, '{"user":{'
end
test 'sign in with json format is idempotent' do
get new_user_session_path(format: 'json')
assert_response :success
create_user
post user_session_path(format: 'json'), params: { user: {email: "user@test.com", password: '12345678'} }
assert_response :success
get new_user_session_path(format: 'json')
assert_response :success
post user_session_path(format: 'json'), params: { user: {email: "user@test.com", password: '12345678'} }
assert_response :success
assert_includes response.body, '{"user":{'
end
test 'sign out with html redirects' do
sign_in_as_user
delete destroy_user_session_path
assert_response :redirect
assert_current_url '/'
sign_in_as_user
delete destroy_user_session_path(format: 'html')
assert_response :redirect
assert_current_url '/'
end
test 'sign out with json format returns no content' do
sign_in_as_user
delete destroy_user_session_path(format: 'json')
assert_response :no_content
assert_not warden.authenticated?(:user)
end
test 'sign out with non-navigational format via XHR does not redirect' do
swap Devise, navigational_formats: ['*/*', :html] do
sign_in_as_admin
get destroy_sign_out_via_get_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "application/json,text/javascript,*/*" } # NOTE: Bug is triggered by combination of XHR and */*.
assert_response :no_content
assert_not warden.authenticated?(:user)
end
end
# Belt and braces ... Perhaps this test is not necessary?
test 'sign out with navigational format via XHR does redirect' do
swap Devise, navigational_formats: ['*/*', :html] do
sign_in_as_user
delete destroy_user_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "text/html,*/*" }
assert_response :redirect
assert_not warden.authenticated?(:user)
end
end
end
class AuthenticationKeysTest < Devise::IntegrationTest
test 'missing authentication keys cause authentication to abort' do
swap Devise, authentication_keys: [:subdomain] do
sign_in_as_user
assert_contain "Invalid subdomain or password."
assert_not warden.authenticated?(:user)
end
end
test 'missing authentication keys cause authentication to abort unless marked as not required' do
swap Devise, authentication_keys: { email: true, subdomain: false } do
sign_in_as_user
assert warden.authenticated?(:user)
end
end
end
class AuthenticationRequestKeysTest < Devise::IntegrationTest
test 'request keys are used on authentication' do
host! 'foo.bar.baz'
swap Devise, request_keys: [:subdomain] do
User.expects(:find_for_authentication).with({ subdomain: 'foo', email: 'user@test.com' }).returns(create_user)
sign_in_as_user
assert warden.authenticated?(:user)
end
end
test 'invalid request keys raises NoMethodError' do
swap Devise, request_keys: [:unknown_method] do
assert_raise NoMethodError do
sign_in_as_user
end
assert_not warden.authenticated?(:user)
end
end
test 'blank request keys cause authentication to abort' do
host! 'test.com'
swap Devise, request_keys: [:subdomain] do
sign_in_as_user
assert_contain "Invalid email or password."
assert_not warden.authenticated?(:user)
end
end
test 'blank request keys cause authentication to abort unless if marked as not required' do
host! 'test.com'
swap Devise, request_keys: { subdomain: false } do
sign_in_as_user
assert warden.authenticated?(:user)
end
end
end
class AuthenticationSignOutViaTest < Devise::IntegrationTest
def sign_in!(scope)
sign_in_as_admin(visit: send("new_#{scope}_session_path"))
assert warden.authenticated?(scope)
end
test 'allow sign out via delete when sign_out_via provides only delete' do
sign_in!(:sign_out_via_delete)
delete destroy_sign_out_via_delete_session_path
assert_not warden.authenticated?(:sign_out_via_delete)
end
test 'do not allow sign out via get when sign_out_via provides only delete' do
sign_in!(:sign_out_via_delete)
assert_raise ActionController::RoutingError do
get destroy_sign_out_via_delete_session_path
end
assert warden.authenticated?(:sign_out_via_delete)
end
test 'allow sign out via post when sign_out_via provides only post' do
sign_in!(:sign_out_via_post)
post destroy_sign_out_via_post_session_path
assert_not warden.authenticated?(:sign_out_via_post)
end
test 'do not allow sign out via get when sign_out_via provides only post' do
sign_in!(:sign_out_via_post)
assert_raise ActionController::RoutingError do
get destroy_sign_out_via_delete_session_path
end
assert warden.authenticated?(:sign_out_via_post)
end
test 'allow sign out via delete when sign_out_via provides delete and post' do
sign_in!(:sign_out_via_delete_or_post)
delete destroy_sign_out_via_delete_or_post_session_path
assert_not warden.authenticated?(:sign_out_via_delete_or_post)
end
test 'allow sign out via post when sign_out_via provides delete and post' do
sign_in!(:sign_out_via_delete_or_post)
post destroy_sign_out_via_delete_or_post_session_path
assert_not warden.authenticated?(:sign_out_via_delete_or_post)
end
test 'do not allow sign out via get when sign_out_via provides delete and post' do
sign_in!(:sign_out_via_delete_or_post)
assert_raise ActionController::RoutingError do
get destroy_sign_out_via_delete_or_post_session_path
end
assert warden.authenticated?(:sign_out_via_delete_or_post)
end
end
class DoubleAuthenticationRedirectTest < Devise::IntegrationTest
test 'signed in as user redirects when visiting user sign in page' do
sign_in_as_user
get new_user_session_path(format: :html)
assert_redirected_to '/'
end
test 'signed in as admin redirects when visiting admin sign in page' do
sign_in_as_admin
get new_admin_session_path(format: :html)
assert_redirected_to '/admin_area/home'
end
test 'signed in as both user and admin redirects when visiting admin sign in page' do
sign_in_as_user
sign_in_as_admin
get new_user_session_path(format: :html)
assert_redirected_to '/'
get new_admin_session_path(format: :html)
assert_redirected_to '/admin_area/home'
end
end
class DoubleSignOutRedirectTest < Devise::IntegrationTest
test 'sign out after already having signed out redirects to sign in' do
sign_in_as_user
post destroy_sign_out_via_delete_or_post_session_path
get root_path
assert_contain 'Signed out successfully.'
post destroy_sign_out_via_delete_or_post_session_path
get root_path
assert_contain 'Signed out successfully.'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/confirmable_test.rb | test/integration/confirmable_test.rb | # frozen_string_literal: true
require 'test_helper'
class ConfirmationTest < Devise::IntegrationTest
def visit_user_confirmation_with_token(confirmation_token)
visit user_confirmation_path(confirmation_token: confirmation_token)
end
def resend_confirmation
user = create_user(confirm: false)
ActionMailer::Base.deliveries.clear
visit new_user_session_path
click_link "Didn't receive confirmation instructions?"
fill_in 'email', with: user.email
click_button 'Resend confirmation instructions'
end
test 'user should be able to request a new confirmation' do
resend_confirmation
assert_current_url '/users/sign_in'
assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes'
assert_equal 1, ActionMailer::Base.deliveries.size
assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from
end
test 'user should receive a confirmation from a custom mailer' do
User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
resend_confirmation
assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from
end
test 'user with invalid confirmation token should not be able to confirm an account' do
visit_user_confirmation_with_token('invalid_confirmation')
assert_have_selector '#error_explanation'
assert_contain %r{Confirmation token(.*)invalid}
end
test 'user with valid confirmation token should not be able to confirm an account after the token has expired' do
swap Devise, confirm_within: 3.days do
user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
assert_not user.confirmed?
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_have_selector '#error_explanation'
assert_contain %r{needs to be confirmed within 3 days}
assert_not user.reload.confirmed?
assert_current_url "/users/confirmation?confirmation_token=#{user.raw_confirmation_token}"
end
end
test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine it should raise an error' do
user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
swap Devise, confirm_within: 3.days, router_name: :fake_engine do
assert_raise ActionView::Template::Error do
visit_user_confirmation_with_token(user.raw_confirmation_token)
end
end
end
test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine and route overrides back to main it shows the path' do
user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
swap Devise, confirm_within: 3.days, router_name: :fake_engine do
visit user_on_main_app_confirmation_path(confirmation_token: user.raw_confirmation_token)
assert_current_url "/user_on_main_apps/confirmation?confirmation_token=#{user.raw_confirmation_token}"
end
end
test 'user with valid confirmation token where the token has expired with router overrides different engine it shows the path' do
user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
swap Devise, confirm_within: 3.days do
visit user_on_engine_confirmation_path(confirmation_token: user.raw_confirmation_token)
assert_current_url "/user_on_engines/confirmation?confirmation_token=#{user.raw_confirmation_token}"
end
end
test 'user with valid confirmation token should be able to confirm an account before the token has expired' do
swap Devise, confirm_within: 3.days do
user = create_user(confirm: false, confirmation_sent_at: 2.days.ago)
assert_not user.confirmed?
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_contain 'Your email address has been successfully confirmed.'
assert_current_url '/users/sign_in'
assert user.reload.confirmed?
end
end
test 'user should be redirected to a custom path after confirmation' do
Devise::ConfirmationsController.any_instance.stubs(:after_confirmation_path_for).returns("/?custom=1")
user = create_user(confirm: false)
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_current_url "/?custom=1"
end
test 'already confirmed user should not be able to confirm the account again' do
user = create_user(confirm: false)
user.confirmed_at = Time.now
user.save
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_have_selector '#error_explanation'
assert_contain 'already confirmed'
end
test 'already confirmed user should not be able to confirm the account again neither request confirmation' do
user = create_user(confirm: false)
user.confirmed_at = Time.now
user.save
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_contain 'already confirmed'
fill_in 'email', with: user.email
click_button 'Resend confirmation instructions'
assert_contain 'already confirmed'
end
test 'not confirmed user with setup to block without confirmation should not be able to sign in' do
swap Devise, allow_unconfirmed_access_for: 0.days do
sign_in_as_user(confirm: false)
assert_contain 'You have to confirm your email address before continuing'
assert_not warden.authenticated?(:user)
end
end
test 'not confirmed user redirect respects i18n locale set' do
swap Devise, allow_unconfirmed_access_for: 0.days do
sign_in_as_user(confirm: false, visit: new_user_session_path(locale: "pt-BR"))
assert_contain 'Você precisa confirmar seu email para continuar'
assert_not warden.authenticated?(:user)
end
end
test 'not confirmed user should not see confirmation message if invalid credentials are given' do
swap Devise, allow_unconfirmed_access_for: 0.days do
sign_in_as_user(confirm: false) do
fill_in 'password', with: 'invalid'
end
assert_contain 'Invalid email or password'
assert_not warden.authenticated?(:user)
end
end
test 'not confirmed user but configured with some days to confirm should be able to sign in' do
swap Devise, allow_unconfirmed_access_for: 1.day do
sign_in_as_user(confirm: false)
assert_response :success
assert warden.authenticated?(:user)
end
end
test 'unconfirmed but signed in user should be redirected to their root path' do
swap Devise, allow_unconfirmed_access_for: 1.day do
user = sign_in_as_user(confirm: false)
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_contain 'Your email address has been successfully confirmed.'
assert_current_url '/'
end
end
test 'user should be redirected to sign in page whenever signed in as another resource at same session already' do
sign_in_as_admin
user = create_user(confirm: false)
visit_user_confirmation_with_token(user.raw_confirmation_token)
assert_current_url '/users/sign_in'
end
test "should not be able to confirm an email with a blank confirmation token" do
visit_user_confirmation_with_token("")
assert_contain %r{Confirmation token can['’]t be blank}
end
test "should not be able to confirm an email with a nil confirmation token" do
visit_user_confirmation_with_token(nil)
assert_contain %r{Confirmation token can['’]t be blank}
end
test "should not be able to confirm user with blank confirmation token" do
user = create_user(confirm: false)
user.update_attribute(:confirmation_token, "")
visit_user_confirmation_with_token("")
assert_contain %r{Confirmation token can['’]t be blank}
end
test "should not be able to confirm user with nil confirmation token" do
user = create_user(confirm: false)
user.update_attribute(:confirmation_token, nil)
visit_user_confirmation_with_token(nil)
assert_contain %r{Confirmation token can['’]t be blank}
end
test 'error message is configurable by resource name' do
store_translations :en, devise: {
failure: { user: { unconfirmed: "Not confirmed user" } }
} do
sign_in_as_user(confirm: false)
assert_contain 'Not confirmed user'
end
end
test 'resent confirmation token with valid e-mail in JSON format should return empty and valid response' do
user = create_user(confirm: false)
post user_confirmation_path(format: 'json'), params: { user: { email: user.email } }
assert_response :success
assert_equal({}.to_json, response.body)
end
test 'resent confirmation token with invalid e-mail in JSON format should return invalid response' do
create_user(confirm: false)
post user_confirmation_path(format: 'json'), params: { user: { email: 'invalid.test@test.com' } }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
end
test 'confirm account with valid confirmation token in JSON format should return valid response' do
user = create_user(confirm: false)
get user_confirmation_path(confirmation_token: user.raw_confirmation_token, format: 'json')
assert_response :success
assert_includes response.body, '{"user":{'
end
test 'confirm account with invalid confirmation token in JSON format should return invalid response' do
create_user(confirm: false)
get user_confirmation_path(confirmation_token: 'invalid_confirmation', format: 'json')
assert_response :unprocessable_entity
assert_includes response.body, '{"confirmation_token":['
end
test "when in paranoid mode and with a valid e-mail, should not say that the e-mail is valid" do
swap Devise, paranoid: true do
user = create_user(confirm: false)
visit new_user_session_path
click_link "Didn't receive confirmation instructions?"
fill_in 'email', with: user.email
click_button 'Resend confirmation instructions'
assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
assert_current_url "/users/sign_in"
end
end
test "when in paranoid mode and with a invalid e-mail, should not say that the e-mail is invalid" do
swap Devise, paranoid: true do
visit new_user_session_path
click_link "Didn't receive confirmation instructions?"
fill_in 'email', with: "idonthavethisemail@gmail.com"
click_button 'Resend confirmation instructions'
assert_not_contain "1 error prohibited this user from being saved:"
assert_not_contain "Email not found"
assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
assert_current_url "/users/sign_in"
end
end
end
class ConfirmationOnChangeTest < Devise::IntegrationTest
def create_second_admin(options = {})
@admin = nil
create_admin(options)
end
def visit_admin_confirmation_with_token(confirmation_token)
visit admin_confirmation_path(confirmation_token: confirmation_token)
end
test 'admin should be able to request a new confirmation after email changed' do
admin = create_admin
admin.update(email: 'new_test@example.com')
visit new_admin_session_path
click_link "Didn't receive confirmation instructions?"
fill_in 'email', with: admin.unconfirmed_email
assert_difference "ActionMailer::Base.deliveries.size" do
click_button 'Resend confirmation instructions'
end
assert_current_url '/admin_area/sign_in'
assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes'
end
test 'admin with valid confirmation token should be able to confirm email after email changed' do
admin = create_admin
admin.update(email: 'new_test@example.com')
assert_equal 'new_test@example.com', admin.unconfirmed_email
visit_admin_confirmation_with_token(admin.raw_confirmation_token)
assert_contain 'Your email address has been successfully confirmed.'
assert_current_url '/admin_area/sign_in'
assert admin.reload.confirmed?
assert_not admin.reload.pending_reconfirmation?
end
test 'admin with previously valid confirmation token should not be able to confirm email after email changed again' do
admin = create_admin
admin.update(email: 'first_test@example.com')
assert_equal 'first_test@example.com', admin.unconfirmed_email
raw_confirmation_token = admin.raw_confirmation_token
admin = Admin.find(admin.id)
admin.update(email: 'second_test@example.com')
assert_equal 'second_test@example.com', admin.unconfirmed_email
visit_admin_confirmation_with_token(raw_confirmation_token)
assert_have_selector '#error_explanation'
assert_contain(/Confirmation token(.*)invalid/)
visit_admin_confirmation_with_token(admin.raw_confirmation_token)
assert_contain 'Your email address has been successfully confirmed.'
assert_current_url '/admin_area/sign_in'
assert admin.reload.confirmed?
assert_not admin.reload.pending_reconfirmation?
end
test 'admin email should be unique also within unconfirmed_email' do
admin = create_admin
admin.update(email: 'new_admin_test@example.com')
assert_equal 'new_admin_test@example.com', admin.unconfirmed_email
create_second_admin(email: "new_admin_test@example.com")
visit_admin_confirmation_with_token(admin.raw_confirmation_token)
assert_have_selector '#error_explanation'
assert_contain(/Email.*already.*taken/)
assert admin.reload.pending_reconfirmation?
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/integration/recoverable_test.rb | test/integration/recoverable_test.rb | # frozen_string_literal: true
require 'test_helper'
class PasswordTest < Devise::IntegrationTest
def visit_new_password_path
visit new_user_session_path
click_link 'Forgot your password?'
end
def request_forgot_password(&block)
visit_new_password_path
assert_response :success
assert_not warden.authenticated?(:user)
fill_in 'email', with: 'user@test.com'
yield if block_given?
Devise.stubs(:friendly_token).returns("abcdef")
click_button 'Send me password reset instructions'
end
def reset_password(options = {}, &block)
unless options[:visit] == false
visit edit_user_password_path(reset_password_token: options[:reset_password_token] || "abcdef")
assert_response :success
end
fill_in 'New password', with: '987654321'
fill_in 'Confirm new password', with: '987654321'
yield if block_given?
click_button 'Change my password'
end
test 'reset password should send to user record email and avoid case mapping collisions' do
create_user(email: 'user@github.com')
request_forgot_password do
fill_in 'email', with: 'user@gıthub.com'
end
mail = ActionMailer::Base.deliveries.last
assert_equal ['user@github.com'], mail.to
end
test 'reset password with email of different case should succeed when email is in the list of case insensitive keys' do
create_user(email: 'Foo@Bar.com')
request_forgot_password do
fill_in 'email', with: 'foo@bar.com'
end
assert_current_url '/users/sign_in'
assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
end
test 'reset password with email should send an email from a custom mailer' do
create_user(email: 'Foo@Bar.com')
User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
request_forgot_password do
fill_in 'email', with: 'foo@bar.com'
end
mail = ActionMailer::Base.deliveries.last
assert_equal ['custom@example.com'], mail.from
assert_match edit_user_password_path(reset_password_token: 'abcdef'), mail.body.encoded
end
test 'reset password with email of different case should fail when email is NOT the list of case insensitive keys' do
swap Devise, case_insensitive_keys: [] do
create_user(email: 'Foo@Bar.com')
request_forgot_password do
fill_in 'email', with: 'foo@bar.com'
end
assert_response :success
assert_current_url '/users/password'
assert_have_selector "input[type=email][value='foo@bar.com']"
assert_contain 'not found'
end
end
test 'reset password with email with extra whitespace should succeed when email is in the list of strip whitespace keys' do
create_user(email: 'foo@bar.com')
request_forgot_password do
fill_in 'email', with: ' foo@bar.com '
end
assert_current_url '/users/sign_in'
assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
end
test 'reset password with email with extra whitespace should fail when email is NOT the list of strip whitespace keys' do
swap Devise, strip_whitespace_keys: [] do
create_user(email: 'foo@bar.com')
request_forgot_password do
fill_in 'email', with: ' foo@bar.com '
end
assert_response :success
assert_current_url '/users/password'
assert_have_selector "input[type=email][value=' foo@bar.com ']"
assert_contain 'not found'
end
end
test 'authenticated user should not be able to visit forgot password page' do
sign_in_as_user
assert warden.authenticated?(:user)
get new_user_password_path
assert_response :redirect
assert_redirected_to root_path
end
test 'not authenticated user should be able to request a forgot password' do
create_user
request_forgot_password
assert_current_url '/users/sign_in'
assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
end
test 'not authenticated user with invalid email should receive an error message' do
request_forgot_password do
fill_in 'email', with: 'invalid.test@test.com'
end
assert_response :success
assert_current_url '/users/password'
assert_have_selector "input[type=email][value='invalid.test@test.com']"
assert_contain 'not found'
end
test 'authenticated user should not be able to visit edit password page' do
sign_in_as_user
get edit_user_password_path
assert_response :redirect
assert_redirected_to root_path
assert warden.authenticated?(:user)
end
test 'not authenticated user without a reset password token should not be able to visit the page' do
get edit_user_password_path
assert_response :redirect
assert_redirected_to "/users/sign_in"
end
test 'not authenticated user with invalid reset password token should not be able to change their password' do
user = create_user
reset_password reset_password_token: 'invalid_reset_password'
assert_response :success
assert_current_url '/users/password'
assert_have_selector '#error_explanation'
assert_contain %r{Reset password token(.*)invalid}
assert_not user.reload.valid_password?('987654321')
end
test 'not authenticated user with valid reset password token but invalid password should not be able to change their password' do
user = create_user
request_forgot_password
reset_password do
fill_in 'Confirm new password', with: 'other_password'
end
assert_response :success
assert_current_url '/users/password'
assert_have_selector '#error_explanation'
assert_contain %r{Password confirmation doesn['’]t match Password}
assert_not user.reload.valid_password?('987654321')
end
test 'not authenticated user with valid data should be able to change their password' do
user = create_user
request_forgot_password
reset_password
assert_current_url '/'
assert_contain 'Your password has been changed successfully. You are now signed in.'
assert user.reload.valid_password?('987654321')
end
test 'after entering invalid data user should still be able to change their password' do
user = create_user
request_forgot_password
reset_password { fill_in 'Confirm new password', with: 'other_password' }
assert_response :success
assert_have_selector '#error_explanation'
assert_not user.reload.valid_password?('987654321')
reset_password visit: false
assert_contain 'Your password has been changed successfully.'
assert user.reload.valid_password?('987654321')
end
test 'sign in user automatically after changing its password' do
create_user
request_forgot_password
reset_password
assert warden.authenticated?(:user)
end
test 'does not sign in user automatically after changing its password if config.sign_in_after_reset_password is false' do
swap Devise, sign_in_after_reset_password: false do
create_user
request_forgot_password
reset_password
assert_contain 'Your password has been changed successfully.'
assert_not_contain 'You are now signed in.'
assert_equal new_user_session_path, @request.path
assert_not warden.authenticated?(:user)
end
end
test 'does not sign in user automatically after changing its password if resource_class.sign_in_after_reset_password is false' do
swap_model_config User, sign_in_after_reset_password: false do
create_user
request_forgot_password
reset_password
assert_contain 'Your password has been changed successfully'
assert_not_contain 'You are now signed in.'
assert_equal new_user_session_path, @request.path
assert_not warden.authenticated?(:user)
end
end
test 'sign in user automatically after changing its password if resource_class.sign_in_after_reset_password is true' do
swap Devise, sign_in_after_reset_password: false do
swap_model_config User, sign_in_after_reset_password: true do
create_user
request_forgot_password
reset_password
assert warden.authenticated?(:user)
end
end
end
test 'does not sign in user automatically after changing its password if it\'s locked and unlock strategy is :none or :time' do
[:none, :time].each do |strategy|
swap Devise, unlock_strategy: strategy do
create_user(locked: true)
request_forgot_password
reset_password
assert_contain 'Your password has been changed successfully.'
assert_not_contain 'You are now signed in.'
assert_equal new_user_session_path, @request.path
assert_not warden.authenticated?(:user)
end
end
end
test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :email' do
swap Devise, unlock_strategy: :email do
user = create_user(locked: true)
request_forgot_password
reset_password
assert_contain 'Your password has been changed successfully.'
assert_not user.reload.access_locked?
assert warden.authenticated?(:user)
end
end
test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :both' do
swap Devise, unlock_strategy: :both do
user = create_user(locked: true)
request_forgot_password
reset_password
assert_contain 'Your password has been changed successfully.'
assert_not user.reload.access_locked?
assert warden.authenticated?(:user)
end
end
test 'reset password request with valid e-mail in JSON format should return empty and valid response' do
create_user
post user_password_path(format: 'json'), params: { user: {email: "user@test.com"} }
assert_response :success
assert_equal({}.to_json, response.body)
end
test 'reset password request with invalid e-mail in JSON format should return valid response' do
create_user
post user_password_path(format: 'json'), params: { user: {email: "invalid.test@test.com"} }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
end
test 'reset password request with invalid e-mail in JSON format should return empty and valid response in paranoid mode' do
swap Devise, paranoid: true do
create_user
post user_password_path(format: 'json'), params: { user: {email: "invalid@test.com"} }
assert_response :success
assert_equal({}.to_json, response.body)
end
end
test 'change password with valid parameters in JSON format should return valid response' do
create_user
request_forgot_password
put user_password_path(format: 'json'), params: { user: {
reset_password_token: 'abcdef', password: '987654321', password_confirmation: '987654321'
} }
assert_response :success
assert warden.authenticated?(:user)
end
test 'change password with invalid token in JSON format should return invalid response' do
create_user
request_forgot_password
put user_password_path(format: 'json'), params: { user: {reset_password_token: 'invalid.token', password: '987654321', password_confirmation: '987654321'} }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
end
test 'change password with invalid new password in JSON format should return invalid response' do
user = create_user
request_forgot_password
put user_password_path(format: 'json'), params: { user: {reset_password_token: user.reload.reset_password_token, password: '', password_confirmation: '987654321'} }
assert_response :unprocessable_entity
assert_includes response.body, '{"errors":{'
end
test "when in paranoid mode and with an invalid e-mail, asking to reset a password should display a message that does not indicates that the e-mail does not exists in the database" do
swap Devise, paranoid: true do
visit_new_password_path
fill_in "email", with: "arandomemail@test.com"
click_button 'Send me password reset instructions'
assert_not_contain "1 error prohibited this user from being saved:"
assert_not_contain "Email not found"
assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
assert_current_url "/users/sign_in"
end
end
test "when in paranoid mode and with a valid e-mail, asking to reset password should display a message that does not indicates that the email exists in the database and redirect to the failure route" do
swap Devise, paranoid: true do
user = create_user
visit_new_password_path
fill_in 'email', with: user.email
click_button 'Send me password reset instructions'
assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
assert_current_url "/users/sign_in"
end
end
test "after recovering a password, should set failed attempts to 0" do
user = create_user
user.update_attribute(:failed_attempts, 10)
assert_equal 10, user.failed_attempts
request_forgot_password
reset_password
assert warden.authenticated?(:user)
user.reload
assert_equal 0, user.failed_attempts
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/helpers/devise_helper_test.rb | test/helpers/devise_helper_test.rb | # frozen_string_literal: true
require 'test_helper'
class DeviseHelperTest < Devise::IntegrationTest
setup do
model_labels = { models: { user: "the user" } }
translations = {
errors: { messages: { not_saved: {
one: "Can't save %{resource} because of 1 error",
other: "Can't save %{resource} because of %{count} errors",
} } },
activerecord: model_labels,
mongoid: model_labels
}
I18n.available_locales
I18n.backend.store_translations(:en, translations)
end
teardown do
I18n.reload!
end
test 'test errors.messages.not_saved with single error from i18n' do
get new_user_registration_path
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user123'
click_button 'Sign up'
assert_have_selector '#error_explanation'
assert_contain "Can't save the user because of 1 error"
end
test 'test errors.messages.not_saved with multiple errors from i18n' do
get new_user_registration_path
fill_in 'email', with: 'invalid_email'
fill_in 'password', with: 'new_user123'
fill_in 'password confirmation', with: 'new_user321'
click_button 'Sign up'
assert_have_selector '#error_explanation'
assert_contain "Can't save the user because of 2 errors"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/helper_methods_test.rb | test/controllers/helper_methods_test.rb | # frozen_string_literal: true
require 'test_helper'
class ApiController < ActionController::Metal
include Devise::Controllers::Helpers
end
class HelperMethodsTest < Devise::ControllerTestCase
tests ApiController
test 'includes Devise::Controllers::Helpers' do
assert_includes @controller.class.ancestors, Devise::Controllers::Helpers
end
test 'does not respond_to helper or helper_method' do
assert_not_respond_to @controller.class, :helper
assert_not_respond_to @controller.class, :helper_method
end
test 'defines methods like current_user' do
assert_respond_to @controller, :current_user
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/sessions_controller_test.rb | test/controllers/sessions_controller_test.rb | # frozen_string_literal: true
require 'test_helper'
class SessionsControllerTest < Devise::ControllerTestCase
tests Devise::SessionsController
include Devise::Test::ControllerHelpers
test "#create doesn't raise unpermitted params when sign in fails" do
begin
subscriber = ActiveSupport::Notifications.subscribe %r{unpermitted_parameters} do |name, start, finish, id, payload|
flunk "Unpermitted params: #{payload}"
end
request.env["devise.mapping"] = Devise.mappings[:user]
request.session["user_return_to"] = 'foo.bar'
create_user
post :create, params: { user: {
email: "wrong@email.com",
password: "wrongpassword"
}
}
assert_equal 200, @response.status
ensure
ActiveSupport::Notifications.unsubscribe(subscriber)
end
end
test "#create works even with scoped views" do
swap Devise, scoped_views: true do
request.env["devise.mapping"] = Devise.mappings[:user]
post :create
assert_equal 200, @response.status
assert_template "users/sessions/new"
end
end
test "#create delete the url stored in the session if the requested format is navigational" do
request.env["devise.mapping"] = Devise.mappings[:user]
request.session["user_return_to"] = 'foo.bar'
user = create_user
user.confirm
post :create, params: { user: {
email: user.email,
password: user.password
}
}
assert_nil request.session["user_return_to"]
end
test "#create doesn't delete the url stored in the session if the requested format is not navigational" do
request.env["devise.mapping"] = Devise.mappings[:user]
request.session["user_return_to"] = 'foo.bar'
user = create_user
user.confirm
post :create, params: { format: 'json', user: {
email: user.email,
password: user.password
}
}
assert_equal 'foo.bar', request.session["user_return_to"]
end
test "#create doesn't raise exception after Warden authentication fails when TestHelpers included" do
request.env["devise.mapping"] = Devise.mappings[:user]
post :create, params: { user: {
email: "nosuchuser@example.com",
password: "wevdude"
}
}
assert_equal 200, @response.status
assert_template "devise/sessions/new"
end
test "#destroy doesn't set the flash and returns 204 status if the requested format is not navigational" do
request.env["devise.mapping"] = Devise.mappings[:user]
user = create_user
user.confirm
post :create, params: { format: 'json', user: {
email: user.email,
password: user.password
}
}
delete :destroy, format: 'json'
assert flash[:notice].blank?, "flash[:notice] should be blank, not #{flash[:notice].inspect}"
assert_equal 204, @response.status
end
test "#destroy returns 401 status if user is not signed in and the requested format is not navigational" do
request.env["devise.mapping"] = Devise.mappings[:user]
delete :destroy, format: 'json'
assert_equal 401, @response.status
end
test "#destroy returns 302 status if user is not signed in and the requested format is navigational" do
request.env["devise.mapping"] = Devise.mappings[:user]
delete :destroy
assert_equal 302, @response.status
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/custom_registrations_controller_test.rb | test/controllers/custom_registrations_controller_test.rb | # frozen_string_literal: true
require 'test_helper'
class CustomRegistrationsControllerTest < Devise::ControllerTestCase
tests Custom::RegistrationsController
include Devise::Test::ControllerHelpers
setup do
request.env["devise.mapping"] = Devise.mappings[:user]
@password = 'password'
@user = create_user(password: @password, password_confirmation: @password).tap(&:confirm)
end
test "yield resource to block on create success" do
post :create, params: { user: { email: "user@example.org", password: "password", password_confirmation: "password" } }
assert @controller.create_block_called?, "create failed to yield resource to provided block"
end
test "yield resource to block on create failure" do
post :create, params: { user: { } }
assert @controller.create_block_called?, "create failed to yield resource to provided block"
end
test "yield resource to block on update success" do
sign_in @user
put :update, params: { user: { current_password: @password } }
assert @controller.update_block_called?, "update failed to yield resource to provided block"
end
test "yield resource to block on update failure" do
sign_in @user
put :update, params: { user: { } }
assert @controller.update_block_called?, "update failed to yield resource to provided block"
end
test "yield resource to block on new" do
get :new
assert @controller.new_block_called?, "new failed to yield resource to provided block"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/load_hooks_controller_test.rb | test/controllers/load_hooks_controller_test.rb | # frozen_string_literal: true
require 'test_helper'
class LoadHooksControllerTest < Devise::ControllerTestCase
setup do
ActiveSupport.on_load(:devise_controller) do
define_method :defined_by_load_hook do
puts 'I am defined dynamically by activesupport load hook'
end
end
end
teardown do
DeviseController.class_eval { undef :defined_by_load_hook }
end
test 'load hook called when controller is loaded' do
assert_includes DeviseController.instance_methods, :defined_by_load_hook
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/inherited_controller_i18n_messages_test.rb | test/controllers/inherited_controller_i18n_messages_test.rb | # frozen_string_literal: true
require 'test_helper'
class SessionsInheritedController < Devise::SessionsController
def test_i18n_scope
set_flash_message(:notice, :signed_in)
end
end
class AnotherInheritedController < SessionsInheritedController
protected
def translation_scope
'another'
end
end
class InheritedControllerTest < Devise::ControllerTestCase
tests SessionsInheritedController
def setup
@mock_warden = OpenStruct.new
@controller.request.env['warden'] = @mock_warden
@controller.request.env['devise.mapping'] = Devise.mappings[:user]
end
test 'I18n scope is inherited from Devise::Sessions' do
I18n.expects(:t).with do |message, options|
message == 'user.signed_in' &&
options[:scope] == 'devise.sessions'
end
@controller.test_i18n_scope
end
end
class AnotherInheritedControllerTest < Devise::ControllerTestCase
tests AnotherInheritedController
def setup
@mock_warden = OpenStruct.new
@controller.request.env['warden'] = @mock_warden
@controller.request.env['devise.mapping'] = Devise.mappings[:user]
end
test 'I18n scope is overridden' do
I18n.expects(:t).with do |message, options|
message == 'user.signed_in' &&
options[:scope] == 'another'
end
@controller.test_i18n_scope
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/helpers_test.rb | test/controllers/helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'ostruct'
class ControllerAuthenticatableTest < Devise::ControllerTestCase
tests ApplicationController
def setup
@mock_warden = OpenStruct.new
@controller.request.env['warden'] = @mock_warden
end
test 'provide access to warden instance' do
assert_equal @mock_warden, @controller.warden
end
test 'proxy signed_in?(scope) to authenticate?' do
@mock_warden.expects(:authenticate?).with(scope: :my_scope)
@controller.signed_in?(:my_scope)
end
test 'proxy signed_in?(nil) to authenticate?' do
Devise.mappings.keys.each do |scope| # :user, :admin, :manager
@mock_warden.expects(:authenticate?).with(scope: scope)
end
@controller.signed_in?
end
test 'proxy [group]_signed_in? to authenticate? with each scope' do
[:user, :admin].each do |scope|
@mock_warden.expects(:authenticate?).with(scope: scope).returns(false)
end
@controller.commenter_signed_in?
end
test 'proxy current_user to authenticate with user scope' do
@mock_warden.expects(:authenticate).with(scope: :user)
@controller.current_user
end
test 'proxy current_admin to authenticate with admin scope' do
@mock_warden.expects(:authenticate).with(scope: :admin)
@controller.current_admin
end
test 'proxy current_[group] to authenticate with each scope' do
[:user, :admin].each do |scope|
@mock_warden.expects(:authenticate).with(scope: scope).returns(nil)
end
@controller.current_commenter
end
test 'proxy current_[plural_group] to authenticate with each scope' do
[:user, :admin].each do |scope|
@mock_warden.expects(:authenticate).with(scope: scope)
end
@controller.current_commenters
end
test 'proxy current_publisher_account to authenticate with namespaced publisher account scope' do
@mock_warden.expects(:authenticate).with(scope: :publisher_account)
@controller.current_publisher_account
end
test 'proxy authenticate_user! to authenticate with user scope' do
@mock_warden.expects(:authenticate!).with({ scope: :user, locale: :en })
@controller.authenticate_user!
end
test 'proxy authenticate_user! options to authenticate with user scope' do
@mock_warden.expects(:authenticate!).with({ scope: :user, recall: "foo", locale: :en })
@controller.authenticate_user!(recall: "foo")
end
test 'proxy authenticate_admin! to authenticate with admin scope' do
@mock_warden.expects(:authenticate!).with({ scope: :admin, locale: :en })
@controller.authenticate_admin!
end
test 'proxy authenticate_[group]! to authenticate!? with each scope' do
[:user, :admin].each do |scope|
@mock_warden.expects(:authenticate!).with({ scope: scope, locale: :en })
@mock_warden.expects(:authenticate?).with(scope: scope).returns(false)
end
@controller.authenticate_commenter!
end
test 'proxy authenticate_publisher_account! to authenticate with namespaced publisher account scope' do
@mock_warden.expects(:authenticate!).with({ scope: :publisher_account, locale: :en })
@controller.authenticate_publisher_account!
end
test 'proxy user_signed_in? to authenticate with user scope' do
@mock_warden.expects(:authenticate).with(scope: :user).returns("user")
assert @controller.user_signed_in?
end
test 'proxy admin_signed_in? to authenticatewith admin scope' do
@mock_warden.expects(:authenticate).with(scope: :admin)
assert_not @controller.admin_signed_in?
end
test 'proxy publisher_account_signed_in? to authenticate with namespaced publisher account scope' do
@mock_warden.expects(:authenticate).with(scope: :publisher_account)
@controller.publisher_account_signed_in?
end
test 'proxy user_session to session scope in warden' do
@mock_warden.expects(:authenticate).with(scope: :user).returns(true)
@mock_warden.expects(:session).with(:user).returns({})
@controller.user_session
end
test 'proxy admin_session to session scope in warden' do
@mock_warden.expects(:authenticate).with(scope: :admin).returns(true)
@mock_warden.expects(:session).with(:admin).returns({})
@controller.admin_session
end
test 'proxy publisher_account_session from namespaced scope to session scope in warden' do
@mock_warden.expects(:authenticate).with(scope: :publisher_account).returns(true)
@mock_warden.expects(:session).with(:publisher_account).returns({})
@controller.publisher_account_session
end
test 'sign in proxy to set_user on warden' do
user = User.new
@mock_warden.expects(:user).returns(nil)
@mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true)
@controller.sign_in(:user, user)
end
test 'sign in accepts a resource as argument' do
user = User.new
@mock_warden.expects(:user).returns(nil)
@mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true)
@controller.sign_in(user)
end
test 'does not sign in again if the user is already in' do
user = User.new
@mock_warden.expects(:user).returns(user)
@mock_warden.expects(:set_user).never
assert @controller.sign_in(user)
end
test 'sign in again when the user is already in only if force is given' do
user = User.new
@mock_warden.expects(:user).returns(user)
@mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true)
@controller.sign_in(user, force: true)
end
test 'bypass the sign in' do
user = User.new
@mock_warden.expects(:session_serializer).returns(serializer = mock())
serializer.expects(:store).with(user, :user)
@controller.bypass_sign_in(user)
end
test 'sign out clears up any signed in user from all scopes' do
user = User.new
@mock_warden.expects(:user).times(Devise.mappings.size)
@mock_warden.expects(:logout).with().returns(true)
@controller.instance_variable_set(:@current_user, user)
@controller.instance_variable_set(:@current_admin, user)
@controller.sign_out
assert_nil @controller.instance_variable_get(:@current_user)
assert_nil @controller.instance_variable_get(:@current_admin)
end
test 'sign out logs out and clears up any signed in user by scope' do
user = User.new
@mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(user)
@mock_warden.expects(:logout).with(:user).returns(true)
@mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true)
@controller.instance_variable_set(:@current_user, user)
@controller.sign_out(:user)
assert_nil @controller.instance_variable_get(:@current_user)
end
test 'sign out accepts a resource as argument' do
@mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(true)
@mock_warden.expects(:logout).with(:user).returns(true)
@mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true)
@controller.sign_out(User.new)
end
test 'sign out without args proxy to sign out all scopes' do
@mock_warden.expects(:user).times(Devise.mappings.size)
@mock_warden.expects(:logout).with().returns(true)
@mock_warden.expects(:clear_strategies_cache!).with().returns(true)
@controller.sign_out
end
test 'sign out everybody proxy to logout on warden' do
@mock_warden.expects(:user).times(Devise.mappings.size)
@mock_warden.expects(:logout).with().returns(true)
@controller.sign_out_all_scopes
end
test 'stored location for returns the location for a given scope' do
assert_nil @controller.stored_location_for(:user)
@controller.session[:"user_return_to"] = "/foo.bar"
assert_equal "/foo.bar", @controller.stored_location_for(:user)
end
test 'stored location for accepts a resource as argument' do
assert_nil @controller.stored_location_for(:user)
@controller.session[:"user_return_to"] = "/foo.bar"
assert_equal "/foo.bar", @controller.stored_location_for(User.new)
end
test 'stored location cleans information after reading' do
@controller.session[:"user_return_to"] = "/foo.bar"
assert_equal "/foo.bar", @controller.stored_location_for(:user)
assert_nil @controller.session[:"user_return_to"]
end
test 'store location for stores a location to redirect back to' do
assert_nil @controller.stored_location_for(:user)
@controller.store_location_for(:user, "/foo.bar")
assert_equal "/foo.bar", @controller.stored_location_for(:user)
end
test 'store bad location for stores a location to redirect back to' do
assert_nil @controller.stored_location_for(:user)
@controller.store_location_for(:user, "/foo.bar\">Carry")
assert_nil @controller.stored_location_for(:user)
end
test 'store location for accepts a resource as argument' do
@controller.store_location_for(User.new, "/foo.bar")
assert_equal "/foo.bar", @controller.stored_location_for(User.new)
end
test 'store location for stores paths' do
@controller.store_location_for(:user, "//host/foo.bar")
assert_equal "/foo.bar", @controller.stored_location_for(:user)
@controller.store_location_for(:user, "///foo.bar")
assert_equal "/foo.bar", @controller.stored_location_for(:user)
end
test 'store location for stores query string' do
@controller.store_location_for(:user, "/foo?bar=baz")
assert_equal "/foo?bar=baz", @controller.stored_location_for(:user)
end
test 'store location for stores fragments' do
@controller.store_location_for(:user, "/foo#bar")
assert_equal "/foo#bar", @controller.stored_location_for(:user)
end
test 'after sign in path defaults to root path if none by was specified for the given scope' do
assert_equal root_path, @controller.after_sign_in_path_for(:user)
end
test 'after sign in path defaults to the scoped root path' do
assert_equal admin_root_path, @controller.after_sign_in_path_for(:admin)
end
test 'after sign out path defaults to the root path' do
assert_equal root_path, @controller.after_sign_out_path_for(:admin)
assert_equal root_path, @controller.after_sign_out_path_for(:user)
end
test 'sign in and redirect uses the stored location' do
user = User.new
@controller.session[:user_return_to] = "/foo.bar"
@mock_warden.expects(:user).with(:user).returns(nil)
@mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true)
@controller.expects(:redirect_to).with("/foo.bar")
@controller.sign_in_and_redirect(user)
end
test 'sign in and redirect uses the configured after sign in path' do
admin = Admin.new
@mock_warden.expects(:user).with(:admin).returns(nil)
@mock_warden.expects(:set_user).with(admin, { scope: :admin }).returns(true)
@controller.expects(:redirect_to).with(admin_root_path)
@controller.sign_in_and_redirect(admin)
end
test 'sign in and redirect does not sign in again if user is already signed' do
admin = Admin.new
@mock_warden.expects(:user).with(:admin).returns(admin)
@mock_warden.expects(:set_user).never
@controller.expects(:redirect_to).with(admin_root_path)
@controller.sign_in_and_redirect(admin)
end
test 'sign out and redirect uses the configured after sign out path when signing out only the current scope' do
swap Devise, sign_out_all_scopes: false do
@mock_warden.expects(:user).with(scope: :admin, run_callbacks: false).returns(true)
@mock_warden.expects(:logout).with(:admin).returns(true)
@mock_warden.expects(:clear_strategies_cache!).with(scope: :admin).returns(true)
@controller.expects(:redirect_to).with(admin_root_path)
@controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end"
@controller.sign_out_and_redirect(:admin)
end
end
test 'sign out and redirect uses the configured after sign out path when signing out all scopes' do
swap Devise, sign_out_all_scopes: true do
@mock_warden.expects(:user).times(Devise.mappings.size)
@mock_warden.expects(:logout).with().returns(true)
@mock_warden.expects(:clear_strategies_cache!).with().returns(true)
@controller.expects(:redirect_to).with(admin_root_path)
@controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end"
@controller.sign_out_and_redirect(:admin)
end
end
test 'is_flashing_format? depends on is_navigation_format?' do
@controller.expects(:is_navigational_format?).returns(true)
assert @controller.is_flashing_format?
end
test 'is_flashing_format? is guarded against flash (middleware) not being loaded' do
@controller.request.expects(:respond_to?).with(:flash).returns(false)
assert_not @controller.is_flashing_format?
end
test 'is not a devise controller' do
assert_not @controller.devise_controller?
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/internal_helpers_test.rb | test/controllers/internal_helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
class MyController < DeviseController
end
class HelpersTest < Devise::ControllerTestCase
tests MyController
def setup
@mock_warden = OpenStruct.new
@controller.request.env['warden'] = @mock_warden
@controller.request.env['devise.mapping'] = Devise.mappings[:user]
end
test 'get resource name from env' do
assert_equal :user, @controller.send(:resource_name)
end
test 'get resource class from env' do
assert_equal User, @controller.send(:resource_class)
end
test 'get resource instance variable from env' do
@controller.instance_variable_set(:@user, user = User.new)
assert_equal user, @controller.send(:resource)
end
test 'set resource instance variable from env' do
user = @controller.send(:resource_class).new
@controller.send(:resource=, user)
assert_equal user, @controller.send(:resource)
assert_equal user, @controller.instance_variable_get(:@user)
end
test 'get resource params from request params using resource name as key' do
user_params = {'email' => 'shirley@templar.com'}
# Stub controller name so strong parameters can filter properly.
# DeviseController does not allow any parameters by default.
@controller.stubs(:controller_name).returns(:sessions_controller)
params = ActionController::Parameters.new({'user' => user_params})
@controller.stubs(:params).returns(params)
res_params = @controller.send(:resource_params).permit!.to_h
assert_equal user_params, res_params
end
test 'resources methods are not controller actions' do
assert_empty @controller.class.action_methods.delete_if { |m| m.include? 'commenter' }
end
test 'require no authentication tests current mapping' do
@mock_warden.expects(:authenticate?).with(:rememberable, { scope: :user }).returns(true)
@mock_warden.expects(:user).with(:user).returns(User.new)
@controller.expects(:redirect_to).with(root_path)
@controller.send :require_no_authentication
end
test 'require no authentication only checks if already authenticated if no inputs strategies are available' do
Devise.mappings[:user].expects(:no_input_strategies).returns([])
@mock_warden.expects(:authenticate?).never
@mock_warden.expects(:authenticated?).with(:user).once.returns(true)
@mock_warden.expects(:user).with(:user).returns(User.new)
@controller.expects(:redirect_to).with(root_path)
@controller.send :require_no_authentication
end
test 'require no authentication sets a flash message' do
@mock_warden.expects(:authenticate?).with(:rememberable, { scope: :user }).returns(true)
@mock_warden.expects(:user).with(:user).returns(User.new)
@controller.expects(:redirect_to).with(root_path)
@controller.send :require_no_authentication
assert flash[:alert] == I18n.t("devise.failure.already_authenticated")
end
test 'signed in resource returns signed in resource for current scope' do
@mock_warden.expects(:authenticate).with(scope: :user).returns(User.new)
assert_kind_of User, @controller.send(:signed_in_resource)
end
test 'is a devise controller' do
assert @controller.devise_controller?
end
test 'does not issue blank flash messages' do
I18n.stubs(:t).returns(' ')
@controller.send :set_flash_message, :notice, :send_instructions
assert flash[:notice].nil?
end
test 'issues non-blank flash messages normally' do
I18n.stubs(:t).returns('non-blank')
@controller.send :set_flash_message, :notice, :send_instructions
assert_equal 'non-blank', flash[:notice]
end
test 'issues non-blank flash.now messages normally' do
I18n.stubs(:t).returns('non-blank')
@controller.send :set_flash_message, :notice, :send_instructions, { now: true }
assert_equal 'non-blank', flash.now[:notice]
end
test 'uses custom i18n options' do
@controller.stubs(:devise_i18n_options).returns(default: "devise custom options")
@controller.send :set_flash_message, :notice, :invalid_i18n_messagesend_instructions
assert_equal 'devise custom options', flash[:notice]
end
test 'allows custom i18n options to override resource_name' do
I18n.expects(:t).with("custom_resource_name.confirmed", anything)
@controller.stubs(:devise_i18n_options).returns(resource_name: "custom_resource_name")
@controller.send :set_flash_message, :notice, :confirmed
end
test 'navigational_formats not returning a wild card' do
MyController.send(:public, :navigational_formats)
swap Devise, navigational_formats: ['*/*', :html] do
assert_not @controller.navigational_formats.include?("*/*")
end
MyController.send(:protected, :navigational_formats)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/custom_strategy_test.rb | test/controllers/custom_strategy_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'ostruct'
require 'warden/strategies/base'
require 'devise/test/controller_helpers'
class CustomStrategyController < ActionController::Base
def new
warden.authenticate!(:custom_strategy)
end
end
# These tests are to prove that a warden strategy can successfully
# return a custom response, including a specific status code and
# custom http response headers. This does work in production,
# however, at the time of writing this, the Devise test helpers do
# not recognise the custom response and proceed to calling the
# Failure App. This makes it impossible to write tests for a
# strategy that return a custom response with Devise.
class CustomStrategy < Warden::Strategies::Base
def authenticate!
custom_headers = { "X-FOO" => "BAR" }
response = Rack::Response.new("BAD REQUEST", 400, custom_headers)
custom! response.finish
end
end
class CustomStrategyTest < Devise::ControllerTestCase
tests CustomStrategyController
include Devise::Test::ControllerHelpers
setup do
Warden::Strategies.add(:custom_strategy, CustomStrategy)
end
teardown do
Warden::Strategies._strategies.delete(:custom_strategy)
end
test "custom strategy can return its own status code" do
ret = get :new
# check the returned response
assert ret.is_a?(ActionDispatch::TestResponse)
# check the saved response as well. This is purely so that the response is available to the testing framework
# for verification. In production, the above array would be delivered directly to Rack.
assert_response 400
end
test "custom strategy can return custom headers" do
ret = get :new
# check the returned response
assert ret.is_a?(ActionDispatch::TestResponse)
# check the saved response headers as well.
assert_equal 'BAR', response.headers['X-FOO']
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/passwords_controller_test.rb | test/controllers/passwords_controller_test.rb | # frozen_string_literal: true
require 'test_helper'
class PasswordsControllerTest < Devise::ControllerTestCase
tests Devise::PasswordsController
include Devise::Test::ControllerHelpers
setup do
request.env["devise.mapping"] = Devise.mappings[:user]
@user = create_user.tap(&:confirm)
@raw = @user.send_reset_password_instructions
end
def put_update_with_params
put :update, params: { "user" => {
"reset_password_token" => @raw, "password" => "1234567", "password_confirmation" => "1234567"
}
}
end
test 'redirect to after_sign_in_path_for if after_resetting_password_path_for is not overridden' do
put_update_with_params
assert_redirected_to "http://test.host/"
end
test 'redirect accordingly if after_resetting_password_path_for is overridden' do
custom_path = "http://custom.path/"
Devise::PasswordsController.any_instance.stubs(:after_resetting_password_path_for).with(@user).returns(custom_path)
put_update_with_params
assert_redirected_to custom_path
end
test 'calls after_database_authentication callback after sign_in immediately after password update' do
User.any_instance.expects :after_database_authentication
put_update_with_params
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/controllers/url_helpers_test.rb | test/controllers/url_helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
class RoutesTest < Devise::ControllerTestCase
tests ApplicationController
def assert_path_and_url(name, prepend_path = nil)
@request.path = '/users/session'
prepend_path = "#{prepend_path}_" if prepend_path
# Resource param
assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user),
send(:"#{prepend_path}user_#{name}_path")
assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user),
send(:"#{prepend_path}user_#{name}_url")
# With string
assert_equal @controller.send(:"#{prepend_path}#{name}_path", "user"),
send(:"#{prepend_path}user_#{name}_path")
assert_equal @controller.send(:"#{prepend_path}#{name}_url", "user"),
send(:"#{prepend_path}user_#{name}_url")
# Default url params
assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user, param: 123),
send(:"#{prepend_path}user_#{name}_path", param: 123)
assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user, param: 123),
send(:"#{prepend_path}user_#{name}_url", param: 123)
@request.path = nil
# With an object
assert_equal @controller.send(:"#{prepend_path}#{name}_path", User.new),
send(:"#{prepend_path}user_#{name}_path")
assert_equal @controller.send(:"#{prepend_path}#{name}_url", User.new),
send(:"#{prepend_path}user_#{name}_url")
end
test 'should alias session to mapped user session' do
assert_path_and_url :session
assert_path_and_url :session, :new
assert_path_and_url :session, :destroy
end
test 'should alias password to mapped user password' do
assert_path_and_url :password
assert_path_and_url :password, :new
assert_path_and_url :password, :edit
end
test 'should alias confirmation to mapped user confirmation' do
assert_path_and_url :confirmation
assert_path_and_url :confirmation, :new
end
test 'should alias unlock to mapped user unlock' do
assert_path_and_url :unlock
assert_path_and_url :unlock, :new
end
test 'should alias registration to mapped user registration' do
assert_path_and_url :registration
assert_path_and_url :registration, :new
assert_path_and_url :registration, :edit
assert_path_and_url :registration, :cancel
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/test/controller_helpers_test.rb | test/test/controller_helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
class TestControllerHelpersTest < Devise::ControllerTestCase
tests UsersController
include Devise::Test::ControllerHelpers
test "redirects if attempting to access a page unauthenticated" do
get :index
assert_redirected_to new_user_session_path
assert_equal "You need to sign in or sign up before continuing.", flash[:alert]
end
test "redirects if attempting to access a page with an unconfirmed account" do
swap Devise, allow_unconfirmed_access_for: 0.days do
user = create_user
assert_not user.active_for_authentication?
sign_in user
get :index
assert_redirected_to new_user_session_path
end
end
test "returns nil if accessing current_user with an unconfirmed account" do
swap Devise, allow_unconfirmed_access_for: 0.days do
user = create_user
assert_not user.active_for_authentication?
sign_in user
get :accept, params: { id: user }
assert_nil assigns(:current_user)
end
end
test "does not redirect with valid user" do
user = create_user
user.confirm
sign_in user
get :index
assert_response :success
end
test "does not redirect with valid user after failed first attempt" do
get :index
assert_response :redirect
user = create_user
user.confirm
sign_in user
get :index
assert_response :success
end
test "redirects if valid user signed out" do
user = create_user
user.confirm
sign_in user
get :index
sign_out user
get :index
assert_redirected_to new_user_session_path
end
test "respects custom failure app" do
custom_failure_app = Class.new(Devise::FailureApp) do
def redirect
self.status = 300
end
end
swap Devise.warden_config, failure_app: custom_failure_app do
get :index
assert_response 300
end
end
test "passes given headers from the failure app to the response" do
custom_failure_app = Class.new(Devise::FailureApp) do
def respond
self.status = 401
self.response.headers["CUSTOMHEADER"] = 1
end
end
swap Devise.warden_config, failure_app: custom_failure_app do
sign_in create_user
get :index
assert_equal 1, @response.headers["CUSTOMHEADER"]
end
end
test "returns the body of a failure app" do
get :index
if Devise::Test.rails71_and_up?
assert_empty response.body
else
assert_equal "<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>", response.body
end
end
test "returns the content type of a failure app" do
get :index, params: { format: :json }
assert_includes response.media_type, 'application/json'
end
test "defined Warden after_authentication callback should not be called when sign_in is called" do
begin
Warden::Manager.after_authentication do |user, auth, opts|
flunk "callback was called while it should not"
end
user = create_user
user.confirm
sign_in user
ensure
Warden::Manager._after_set_user.pop
end
end
test "defined Warden before_logout callback should not be called when sign_out is called" do
begin
Warden::Manager.before_logout do |user, auth, opts|
flunk "callback was called while it should not"
end
user = create_user
user.confirm
sign_in user
sign_out user
ensure
Warden::Manager._before_logout.pop
end
end
test "before_failure call should work" do
begin
executed = false
Warden::Manager.before_failure do |env,opts|
executed = true
end
user = create_user
sign_in user
get :index
assert executed
ensure
Warden::Manager._before_failure.pop
end
end
test "allows to sign in with different users" do
first_user = create_user
first_user.confirm
sign_in first_user
get :index
assert_match /User ##{first_user.id}/, @response.body
sign_out first_user
second_user = create_user
second_user.confirm
sign_in second_user
get :index
assert_match /User ##{second_user.id}/, @response.body
end
test "creates a new warden proxy if the request object has changed" do
old_warden_proxy = warden
@request = ActionController::TestRequest.create(Class.new) # needs a "controller class"
new_warden_proxy = warden
assert_not_equal old_warden_proxy, new_warden_proxy
end
test "doesn't create a new warden proxy if the request object hasn't changed" do
old_warden_proxy = warden
new_warden_proxy = warden
assert_equal old_warden_proxy, new_warden_proxy
end
end
class TestControllerHelpersForStreamingControllerTest < Devise::ControllerTestCase
tests StreamingController
include Devise::Test::ControllerHelpers
test "doesn't hang when sending an authentication error response body" do
get :index
if Devise::Test.rails71_and_up?
assert_empty response.body
else
assert_equal "<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>", response.body
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/test/integration_helpers_test.rb | test/test/integration_helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
class TestIntegrationsHelpersTest < Devise::IntegrationTest
include Devise::Test::IntegrationHelpers
test '#sign_in signs in the resource directly' do
sign_in(create_user)
visit '/'
assert warden.authenticated?(:user)
end
test '#sign_outs signs out in the resource directly' do
user = create_user
sign_in user
sign_out user
visit '/'
assert_not warden.authenticated?(:user)
end
test '#sign_out does not signs out other scopes' do
sign_in(create_user)
sign_in(create_admin)
sign_out :user
visit '/'
assert_not warden.authenticated?(:user)
assert warden.authenticated?(:admin)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/trackable_test.rb | test/models/trackable_test.rb | # frozen_string_literal: true
require 'test_helper'
class TrackableTest < ActiveSupport::TestCase
test 'required_fields should contain the fields that Devise uses' do
assert_equal [
:current_sign_in_at,
:current_sign_in_ip,
:last_sign_in_at,
:last_sign_in_ip,
:sign_in_count
], Devise::Models::Trackable.required_fields(User)
end
test 'update_tracked_fields should only set attributes but not save the record' do
user = create_user
request = mock
request.stubs(:remote_ip).returns("127.0.0.1")
assert_nil user.current_sign_in_ip
assert_nil user.last_sign_in_ip
assert_nil user.current_sign_in_at
assert_nil user.last_sign_in_at
assert_equal 0, user.sign_in_count
user.update_tracked_fields(request)
assert_equal "127.0.0.1", user.current_sign_in_ip
assert_equal "127.0.0.1", user.last_sign_in_ip
assert_not_nil user.current_sign_in_at
assert_not_nil user.last_sign_in_at
assert_equal 1, user.sign_in_count
user.reload
assert_nil user.current_sign_in_ip
assert_nil user.last_sign_in_ip
assert_nil user.current_sign_in_at
assert_nil user.last_sign_in_at
assert_equal 0, user.sign_in_count
end
test "update_tracked_fields! should not persist invalid records" do
user = UserWithValidations.new
request = mock
request.stubs(:remote_ip).returns("127.0.0.1")
assert_not user.update_tracked_fields!(request)
assert_not user.persisted?
end
test "update_tracked_fields! should not run model validations" do
user = User.new
request = mock
request.stubs(:remote_ip).returns("127.0.0.1")
user.expects(:after_validation_callback).never
assert_not user.update_tracked_fields!(request)
end
test 'extract_ip_from should be overridable' do
class UserWithOverride < User
protected
def extract_ip_from(request)
"127.0.0.2"
end
end
request = mock
request.stubs(:remote_ip).returns("127.0.0.1")
user = UserWithOverride.new
user.update_tracked_fields(request)
assert_equal "127.0.0.2", user.current_sign_in_ip
assert_equal "127.0.0.2", user.last_sign_in_ip
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/serializable_test.rb | test/models/serializable_test.rb | # frozen_string_literal: true
require 'test_helper'
class SerializableTest < ActiveSupport::TestCase
setup do
@user = create_user
end
test 'should not include unsafe keys on JSON' do
keys = from_json().keys.select{ |key| !key.include?("id") }
assert_equal %w(created_at email facebook_token updated_at username), keys.sort
end
test 'should not include unsafe keys on JSON even if a new except is provided' do
assert_no_key "email", from_json(except: :email)
assert_no_key "confirmation_token", from_json(except: :email)
end
test 'should include unsafe keys on JSON if a force_except is provided' do
assert_no_key "email", from_json(force_except: :email)
assert_key "confirmation_token", from_json(force_except: :email)
end
test 'should not include unsafe keys in inspect' do
assert_match(/email/, @user.inspect)
assert_no_match(/confirmation_token/, @user.inspect)
end
test 'should accept frozen options' do
assert_key "username", @user.as_json({ only: :username, except: [:email].freeze }.freeze)["user"]
end
def assert_key(key, subject)
assert subject.key?(key), "Expected #{subject.inspect} to have key #{key.inspect}"
end
def assert_no_key(key, subject)
assert_not subject.key?(key), "Expected #{subject.inspect} to not have key #{key.inspect}"
end
def from_json(options = nil)
ActiveSupport::JSON.decode(@user.to_json(options))["user"]
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/database_authenticatable_test.rb | test/models/database_authenticatable_test.rb | # frozen_string_literal: true
require 'test_helper'
require 'test_models'
require 'digest/sha1'
class DatabaseAuthenticatableTest < ActiveSupport::TestCase
def setup
setup_mailer
end
test 'should downcase case insensitive keys when saving' do
# case_insensitive_keys is set to :email by default.
email = 'Foo@Bar.com'
user = new_user(email: email)
assert_equal email, user.email
user.save!
assert_equal email.downcase, user.email
end
test 'should downcase case insensitive keys that refer to virtual attributes when saving' do
email = 'Foo@Bar1.com'
confirmation = 'Foo@Bar1.com'
attributes = valid_attributes(email: email, email_confirmation: confirmation)
user = UserWithVirtualAttributes.new(attributes)
assert_equal confirmation, user.email_confirmation
user.save!
assert_equal confirmation.downcase, user.email_confirmation
end
test 'should not mutate value assigned to case insensitive key' do
email = 'Foo@Bar.com'
original_email = email.dup
user = new_user(email: email)
user.save!
assert_equal original_email, email
end
test 'should remove whitespace from strip whitespace keys when saving' do
# strip_whitespace_keys is set to :email by default.
email = ' foo@bar.com '
user = new_user(email: email)
assert_equal email, user.email
user.save!
assert_equal email.strip, user.email
end
test 'should not mutate value assigned to string whitespace key' do
email = ' foo@bar.com '
original_email = email.dup
user = new_user(email: email)
user.save!
assert_equal original_email, email
end
test "doesn't throw exception when globally configured strip_whitespace_keys are not present on a model" do
swap Devise, strip_whitespace_keys: [:fake_key] do
assert_nothing_raised { create_user }
end
end
test "doesn't throw exception when globally configured case_insensitive_keys are not present on a model" do
swap Devise, case_insensitive_keys: [:fake_key] do
assert_nothing_raised { create_user }
end
end
test "param filter should not convert booleans and integer to strings" do
conditions = { "login" => "foo@bar.com", "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) }
conditions = Devise::ParameterFilter.new([], []).filter(conditions)
assert_equal( { "login" => "foo@bar.com", "bool1" => "true", "bool2" => "false", "fixnum" => "123", "will_be_converted" => "1..10" }, conditions)
end
test 'param filter should filter case_insensitive_keys as insensitive' do
conditions = {'insensitive' => 'insensitive_VAL', 'sensitive' => 'sensitive_VAL'}
conditions = Devise::ParameterFilter.new(['insensitive'], []).filter(conditions)
assert_equal( {'insensitive' => 'insensitive_val', 'sensitive' => 'sensitive_VAL'}, conditions )
end
test 'param filter should filter strip_whitespace_keys stripping whitespaces' do
conditions = {'strip_whitespace' => ' strip_whitespace_val ', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}
conditions = Devise::ParameterFilter.new([], ['strip_whitespace']).filter(conditions)
assert_equal( {'strip_whitespace' => 'strip_whitespace_val', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}, conditions )
end
test 'param filter should not add keys to filtered hash' do
conditions = { 'present' => 'present_val' }
conditions.default = ''
conditions = Devise::ParameterFilter.new(['not_present'], []).filter(conditions)
assert_equal({ 'present' => 'present_val' }, conditions)
end
test 'should respond to password and password confirmation' do
user = new_user
assert_respond_to user, :password
assert_respond_to user, :password_confirmation
end
test 'should generate a hashed password while setting password' do
user = new_user
assert_present user.encrypted_password
end
test 'should support custom hashing methods' do
user = UserWithCustomHashing.new(password: '654321')
assert_equal '123456', user.encrypted_password
end
test 'allow authenticatable_salt to work even with nil hashed password' do
user = User.new
user.encrypted_password = nil
assert_nil user.authenticatable_salt
end
test 'should not generate a hashed password if password is blank' do
assert_blank new_user(password: nil).encrypted_password
assert_blank new_user(password: '').encrypted_password
end
test 'should hash password again if password has changed' do
user = create_user
encrypted_password = user.encrypted_password
user.password = user.password_confirmation = 'new_password'
user.save!
assert_not_equal encrypted_password, user.encrypted_password
end
test 'should test for a valid password' do
user = create_user
assert user.valid_password?('12345678')
assert_not user.valid_password?('654321')
end
test 'should not raise error with an empty password' do
user = create_user
user.encrypted_password = ''
assert_nothing_raised { user.valid_password?('12345678') }
end
test 'should be an invalid password if the user has an empty password' do
user = create_user
user.encrypted_password = ''
assert_not user.valid_password?('654321')
end
test 'should respond to current password' do
assert_respond_to new_user, :current_password
end
test 'should update password with valid current password' do
user = create_user
assert user.update_with_password(current_password: '12345678',
password: 'pass4321', password_confirmation: 'pass4321')
assert user.reload.valid_password?('pass4321')
end
test 'should add an error to current password when it is invalid' do
user = create_user
assert_not user.update_with_password(current_password: 'other',
password: 'pass4321', password_confirmation: 'pass4321')
assert user.reload.valid_password?('12345678')
assert_match "is invalid", user.errors[:current_password].join
end
test 'should add an error to current password when it is blank' do
user = create_user
assert_not user.update_with_password(password: 'pass4321',
password_confirmation: 'pass4321')
assert user.reload.valid_password?('12345678')
assert user.errors.added?(:current_password, :blank)
end
test 'should run validations even when current password is invalid or blank' do
user = UserWithValidation.create!(valid_attributes)
user.save
assert user.persisted?
assert_not user.update_with_password(username: "")
assert_match "usertest", user.reload.username
assert user.errors.added?(:username, :blank)
end
test 'should ignore password and its confirmation if they are blank' do
user = create_user
assert user.update_with_password(current_password: '12345678', email: "new@example.com")
assert_equal "new@example.com", user.email
end
test 'should not update password with invalid confirmation' do
user = create_user
assert_not user.update_with_password(current_password: '12345678',
password: 'pass4321', password_confirmation: 'other')
assert user.reload.valid_password?('12345678')
end
test 'should clean up password fields on failure' do
user = create_user
assert_not user.update_with_password(current_password: '12345678',
password: 'pass4321', password_confirmation: 'other')
assert user.password.blank?
assert user.password_confirmation.blank?
end
test 'should update the user without password' do
user = create_user
user.update_without_password(email: 'new@example.com')
assert_equal 'new@example.com', user.email
end
test 'should not update password without password' do
user = create_user
user.update_without_password(password: 'pass4321', password_confirmation: 'pass4321')
assert_not user.reload.valid_password?('pass4321')
assert user.valid_password?('12345678')
end
test 'should destroy user if current password is valid' do
user = create_user
assert user.destroy_with_password('12345678')
assert_not user.persisted?
end
test 'should not destroy user with invalid password' do
user = create_user
assert_not user.destroy_with_password('other')
assert user.persisted?
assert_match "is invalid", user.errors[:current_password].join
end
test 'should not destroy user with blank password' do
user = create_user
assert_not user.destroy_with_password(nil)
assert user.persisted?
assert user.errors.added?(:current_password, :blank)
end
test 'should not email on password change' do
user = create_user
assert_email_not_sent do
assert user.update(password: 'newpass', password_confirmation: 'newpass')
end
end
test 'should notify previous email on email change when configured' do
swap Devise, send_email_changed_notification: true do
user = create_user
original_email = user.email
assert_email_sent original_email do
assert user.update(email: 'new-email@example.com')
end
assert_match original_email, ActionMailer::Base.deliveries.last.body.encoded
end
end
test 'should notify email on password change when configured' do
swap Devise, send_password_change_notification: true do
user = create_user
assert_email_sent user.email do
assert user.update(password: 'newpass', password_confirmation: 'newpass')
end
assert_match user.email, ActionMailer::Base.deliveries.last.body.encoded
end
end
test 'should not notify email on password change even when configured if skip_password_change_notification! is invoked' do
swap Devise, send_password_change_notification: true do
user = create_user
user.skip_password_change_notification!
assert_email_not_sent do
assert user.update(password: 'newpass', password_confirmation: 'newpass')
end
end
end
test 'should not notify email on email change even when configured if skip_email_changed_notification! is invoked' do
swap Devise, send_email_changed_notification: true do
user = create_user
user.skip_email_changed_notification!
assert_email_not_sent do
assert user.update(email: 'new-email@example.com')
end
end
end
test 'downcase_keys with validation' do
User.create(email: "HEllO@example.com", password: "123456")
user = User.create(email: "HEllO@example.com", password: "123456")
assert_not user.valid?
end
test 'required_fields should be encryptable_password and the email field by default' do
assert_equal [
:encrypted_password,
:email
], Devise::Models::DatabaseAuthenticatable.required_fields(User)
end
test 'required_fields should be encryptable_password and the login when the login is on authentication_keys' do
swap Devise, authentication_keys: [:login] do
assert_equal [
:encrypted_password,
:login
], Devise::Models::DatabaseAuthenticatable.required_fields(User)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/validatable_test.rb | test/models/validatable_test.rb | # encoding: UTF-8
# frozen_string_literal: true
require 'test_helper'
class ValidatableTest < ActiveSupport::TestCase
test 'should require email to be set' do
user = new_user(email: nil)
assert user.invalid?
assert user.errors[:email]
assert user.errors.added?(:email, :blank)
end
test 'should require uniqueness of email if email has changed, allowing blank' do
existing_user = create_user
user = new_user(email: '')
assert user.invalid?
assert_no_match(/taken/, user.errors[:email].join)
user.email = existing_user.email
assert user.invalid?
assert_match(/taken/, user.errors[:email].join)
user.save(validate: false)
assert user.valid?
end
test 'should require correct email format if email has changed, allowing blank' do
user = new_user(email: '')
assert user.invalid?
assert_not_equal 'is invalid', user.errors[:email].join
%w{invalid_email_format 123 $$$ () ☃}.each do |email|
user.email = email
assert user.invalid?, "should be invalid with email #{email}"
assert_equal 'is invalid', user.errors[:email].join
end
user.save(validate: false)
assert user.valid?
end
test 'should accept valid emails' do
%w(a.b.c@example.com test_mail@gmail.com any@any.net email@test.br 123@mail.test 1☃3@mail.test).each do |email|
user = new_user(email: email)
assert user.valid?, "should be valid with email #{email}"
assert_blank user.errors[:email]
end
end
test 'should require password to be set when creating a new record' do
user = new_user(password: '', password_confirmation: '')
assert user.invalid?
assert user.errors.added?(:password, :blank)
end
test 'should require confirmation to be set when creating a new record' do
user = new_user(password: 'new_password', password_confirmation: 'blabla')
assert user.invalid?
assert user.errors.added?(:password_confirmation, :confirmation, attribute: "Password")
end
test 'should require password when updating/resetting password' do
user = create_user
user.password = ''
user.password_confirmation = ''
assert user.invalid?
assert user.errors.added?(:password, :blank)
end
test 'should require confirmation when updating/resetting password' do
user = create_user
user.password_confirmation = 'another_password'
assert user.invalid?
assert user.errors.added?(:password_confirmation, :confirmation, attribute: "Password")
end
test 'should require a password with minimum of 7 characters' do
user = new_user(password: '12345', password_confirmation: '12345')
assert user.invalid?
assert_equal 'is too short (minimum is 7 characters)', user.errors[:password].join
end
test 'should require a password with maximum of 72 characters long' do
user = new_user(password: 'x'*73, password_confirmation: 'x'*73)
assert user.invalid?
assert_equal 'is too long (maximum is 72 characters)', user.errors[:password].join
end
test 'should not require password length when it\'s not changed' do
user = create_user.reload
user.password = user.password_confirmation = nil
assert user.valid?
user.password_confirmation = 'confirmation'
assert user.invalid?
assert_not (user.errors[:password].join =~ /is too long/)
end
test 'should complain about length even if password is not required' do
user = new_user(password: 'x'*73, password_confirmation: 'x'*73)
user.stubs(:password_required?).returns(false)
assert user.invalid?
assert_equal 'is too long (maximum is 72 characters)', user.errors[:password].join
end
test 'should not be included in objects with invalid API' do
exception = assert_raise RuntimeError do
Class.new.send :include, Devise::Models::Validatable
end
expected_message = /Could not use :validatable module since .* does not respond to the following methods: validates_presence_of.*/
assert_match expected_message, exception.message
end
test 'required_fields should be an empty array' do
assert_equal [], Devise::Models::Validatable.required_fields(User)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/timeoutable_test.rb | test/models/timeoutable_test.rb | # frozen_string_literal: true
require 'test_helper'
class TimeoutableTest < ActiveSupport::TestCase
test 'should be expired' do
assert new_user.timedout?(31.minutes.ago)
end
test 'should not be expired' do
assert_not new_user.timedout?(29.minutes.ago)
end
test 'should not be expired when params is nil' do
assert_not new_user.timedout?(nil)
end
test 'should use timeout_in method' do
user = new_user
user.instance_eval { def timeout_in; 10.minutes end }
assert user.timedout?(12.minutes.ago)
assert_not user.timedout?(8.minutes.ago)
end
test 'should not be expired when timeout_in method returns nil' do
user = new_user
user.instance_eval { def timeout_in; nil end }
assert_not user.timedout?(10.hours.ago)
end
test 'fallback to Devise config option' do
swap Devise, timeout_in: 1.minute do
user = new_user
assert user.timedout?(2.minutes.ago)
assert_not user.timedout?(30.seconds.ago)
Devise.timeout_in = 5.minutes
assert_not user.timedout?(2.minutes.ago)
assert user.timedout?(6.minutes.ago)
end
end
test 'required_fields should contain the fields that Devise uses' do
assert_equal [], Devise::Models::Timeoutable.required_fields(User)
end
test 'should not raise error if remember_created_at is not empty and rememberable is disabled' do
user = create_admin(remember_created_at: Time.current)
assert user.timedout?(31.minutes.ago)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/omniauthable_test.rb | test/models/omniauthable_test.rb | # frozen_string_literal: true
require 'test_helper'
class OmniauthableTest < ActiveSupport::TestCase
test 'required_fields should contain the fields that Devise uses' do
assert_equal [], Devise::Models::Omniauthable.required_fields(User)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/registerable_test.rb | test/models/registerable_test.rb | # frozen_string_literal: true
require 'test_helper'
class RegisterableTest < ActiveSupport::TestCase
test 'required_fields should contain the fields that Devise uses' do
assert_equal [], Devise::Models::Registerable.required_fields(User)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/lockable_test.rb | test/models/lockable_test.rb | # frozen_string_literal: true
require 'test_helper'
class LockableTest < ActiveSupport::TestCase
def setup
setup_mailer
end
test "should respect maximum attempts configuration" do
user = create_user
user.confirm
swap Devise, maximum_attempts: 2 do
2.times { user.valid_for_authentication?{ false } }
assert user.reload.access_locked?
end
end
test "should increment failed_attempts on successful validation if the user is already locked" do
user = create_user
user.confirm
swap Devise, maximum_attempts: 2 do
2.times { user.valid_for_authentication?{ false } }
assert user.reload.access_locked?
end
user.valid_for_authentication?{ true }
assert_equal 3, user.reload.failed_attempts
end
test "should not touch failed_attempts if lock_strategy is none" do
user = create_user
user.confirm
swap Devise, lock_strategy: :none, maximum_attempts: 2 do
3.times { user.valid_for_authentication?{ false } }
assert_not user.access_locked?
assert_equal 0, user.failed_attempts
end
end
test "should read failed_attempts from database when incrementing" do
user = create_user
initial_failed_attempts = user.failed_attempts
same_user = User.find(user.id)
user.increment_failed_attempts
same_user.increment_failed_attempts
assert_equal initial_failed_attempts + 2, user.reload.failed_attempts
end
test "reset_failed_attempts! updates the failed attempts counter back to 0" do
user = create_user(failed_attempts: 3)
assert_equal 3, user.failed_attempts
user.reset_failed_attempts!
assert_equal 0, user.failed_attempts
user.reset_failed_attempts!
assert_equal 0, user.failed_attempts
end
test "reset_failed_attempts! does not run model validations" do
user = create_user(failed_attempts: 1)
user.expects(:after_validation_callback).never
assert user.reset_failed_attempts!
assert_equal 0, user.failed_attempts
end
test "reset_failed_attempts! does not try to reset if not using failed attempts strategy" do
admin = create_admin
assert_not_respond_to admin, :failed_attempts
assert_not admin.reset_failed_attempts!
end
test 'should be valid for authentication with a unlocked user' do
user = create_user
user.lock_access!
user.unlock_access!
assert user.valid_for_authentication?{ true }
end
test "should verify whether a user is locked or not" do
user = create_user
assert_not user.access_locked?
user.lock_access!
assert user.access_locked?
end
test "active_for_authentication? should be the opposite of locked?" do
user = create_user
user.confirm
assert user.active_for_authentication?
user.lock_access!
assert_not user.active_for_authentication?
end
test "should unlock a user by cleaning locked_at, failed_attempts and unlock_token" do
user = create_user
user.lock_access!
assert_not_nil user.reload.locked_at
assert_not_nil user.reload.unlock_token
user.unlock_access!
assert_nil user.reload.locked_at
assert_nil user.reload.unlock_token
assert_equal 0, user.reload.failed_attempts
end
test "new user should not be locked and should have zero failed_attempts" do
assert_not new_user.access_locked?
assert_equal 0, create_user.failed_attempts
end
test "should unlock user after unlock_in period" do
swap Devise, unlock_in: 3.hours do
user = new_user
user.locked_at = 2.hours.ago
assert user.access_locked?
Devise.unlock_in = 1.hour
assert_not user.access_locked?
end
end
test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do
swap Devise, unlock_strategy: :email do
user = new_user
user.locked_at = 2.hours.ago
assert user.access_locked?
end
end
test "should set unlock_token when locking" do
user = create_user
assert_nil user.unlock_token
user.lock_access!
assert_not_nil user.unlock_token
end
test "should never generate the same unlock token for different users" do
unlock_tokens = []
3.times do
user = create_user
user.lock_access!
token = user.unlock_token
assert_not_includes unlock_tokens, token
unlock_tokens << token
end
end
test "should not generate unlock_token when :email is not an unlock strategy" do
swap Devise, unlock_strategy: :time do
user = create_user
user.lock_access!
assert_nil user.unlock_token
end
end
test "should send email with unlock instructions when :email is an unlock strategy" do
swap Devise, unlock_strategy: :email do
user = create_user
assert_email_sent do
user.lock_access!
end
end
end
test "doesn't send email when you pass option send_instructions to false" do
swap Devise, unlock_strategy: :email do
user = create_user
assert_email_not_sent do
user.lock_access! send_instructions: false
end
end
end
test "sends email when you pass options other than send_instructions" do
swap Devise, unlock_strategy: :email do
user = create_user
assert_email_sent do
user.lock_access! foo: :bar, bar: :foo
end
end
end
test "should not send email with unlock instructions when :email is not an unlock strategy" do
swap Devise, unlock_strategy: :time do
user = create_user
assert_email_not_sent do
user.lock_access!
end
end
end
test 'should find and unlock a user automatically based on raw token' do
user = create_user
raw = user.send_unlock_instructions
locked_user = User.unlock_access_by_token(raw)
assert_equal user, locked_user
assert_not user.reload.access_locked?
end
test 'should return a new record with errors when a invalid token is given' do
locked_user = User.unlock_access_by_token('invalid_token')
assert_not locked_user.persisted?
assert_equal "is invalid", locked_user.errors[:unlock_token].join
end
test 'should return a new record with errors when a blank token is given' do
locked_user = User.unlock_access_by_token('')
assert_not locked_user.persisted?
assert locked_user.errors.added?(:unlock_token, :blank)
end
test 'should find a user to send unlock instructions' do
user = create_user
user.lock_access!
unlock_user = User.send_unlock_instructions(email: user.email)
assert_equal user, unlock_user
end
test 'should return a new user if no email was found' do
unlock_user = User.send_unlock_instructions(email: "invalid@example.com")
assert_not unlock_user.persisted?
end
test 'should add error to new user email if no email was found' do
unlock_user = User.send_unlock_instructions(email: "invalid@example.com")
assert_equal 'not found', unlock_user.errors[:email].join
end
test 'should find a user to send unlock instructions by authentication_keys' do
swap Devise, authentication_keys: [:username, :email] do
user = create_user
unlock_user = User.send_unlock_instructions(email: user.email, username: user.username)
assert_equal user, unlock_user
end
end
test 'should require all unlock_keys' do
swap Devise, unlock_keys: [:username, :email] do
user = create_user
unlock_user = User.send_unlock_instructions(email: user.email)
assert_not unlock_user.persisted?
assert unlock_user.errors.added?(:username, :blank)
end
end
test 'should not be able to send instructions if the user is not locked' do
user = create_user
assert_not user.resend_unlock_instructions
assert_not user.access_locked?
assert_equal 'was not locked', user.errors[:email].join
end
test 'should not be able to send instructions if the user if not locked and have username as unlock key' do
swap Devise, unlock_keys: [:username] do
user = create_user
assert_not user.resend_unlock_instructions
assert_not user.access_locked?
assert_equal 'was not locked', user.errors[:username].join
end
end
test 'should unlock account if lock has expired and increase attempts on failure' do
swap Devise, unlock_in: 1.minute do
user = create_user
user.confirm
user.failed_attempts = 2
user.locked_at = 2.minutes.ago
user.valid_for_authentication? { false }
assert_equal 1, user.failed_attempts
end
end
test 'should unlock account if lock has expired on success' do
swap Devise, unlock_in: 1.minute do
user = create_user
user.confirm
user.failed_attempts = 2
user.locked_at = 2.minutes.ago
user.valid_for_authentication? { true }
assert_equal 0, user.failed_attempts
assert_nil user.locked_at
end
end
test 'required_fields should contain the all the fields when all the strategies are enabled' do
swap Devise, unlock_strategy: :both do
swap Devise, lock_strategy: :failed_attempts do
assert_equal [
:failed_attempts,
:locked_at,
:unlock_token
], Devise::Models::Lockable.required_fields(User)
end
end
end
test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do
swap Devise, unlock_strategy: :time do
swap Devise, lock_strategy: :failed_attempts do
assert_equal [
:failed_attempts,
:locked_at
], Devise::Models::Lockable.required_fields(User)
end
end
end
test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do
swap Devise, unlock_strategy: :email do
swap Devise, lock_strategy: :failed_attempts do
assert_equal [
:failed_attempts,
:unlock_token
], Devise::Models::Lockable.required_fields(User)
end
end
end
test 'should not return a locked unauthenticated message if in paranoid mode' do
swap Devise, paranoid: :true do
user = create_user
user.failed_attempts = Devise.maximum_attempts + 1
user.lock_access!
assert_equal :invalid, user.unauthenticated_message
end
end
test 'should return last attempt message if user made next-to-last attempt of password entering' do
swap Devise, last_attempt_warning: true, lock_strategy: :failed_attempts do
user = create_user
user.failed_attempts = Devise.maximum_attempts - 2
assert_equal :invalid, user.unauthenticated_message
user.failed_attempts = Devise.maximum_attempts - 1
assert_equal :last_attempt, user.unauthenticated_message
user.failed_attempts = Devise.maximum_attempts
assert_equal :locked, user.unauthenticated_message
end
end
test 'should not return last attempt message if last_attempt_warning is disabled' do
swap Devise, last_attempt_warning: false, lock_strategy: :failed_attempts do
user = create_user
user.failed_attempts = Devise.maximum_attempts - 1
assert_equal :invalid, user.unauthenticated_message
end
end
test 'should return locked message if user was programatically locked' do
user = create_user
user.lock_access!
assert_equal :locked, user.unauthenticated_message
end
test 'unlock_strategy_enabled? should return true for both, email, and time strategies if :both is used' do
swap Devise, unlock_strategy: :both do
user = create_user
assert_equal true, user.unlock_strategy_enabled?(:both)
assert_equal true, user.unlock_strategy_enabled?(:time)
assert_equal true, user.unlock_strategy_enabled?(:email)
assert_equal false, user.unlock_strategy_enabled?(:none)
assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy)
end
end
test 'unlock_strategy_enabled? should return true only for the configured strategy' do
swap Devise, unlock_strategy: :email do
user = create_user
assert_equal false, user.unlock_strategy_enabled?(:both)
assert_equal false, user.unlock_strategy_enabled?(:time)
assert_equal true, user.unlock_strategy_enabled?(:email)
assert_equal false, user.unlock_strategy_enabled?(:none)
assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/rememberable_test.rb | test/models/rememberable_test.rb | # frozen_string_literal: true
require 'test_helper'
class RememberableTest < ActiveSupport::TestCase
def resource_class
User
end
def create_resource
create_user
end
test 'remember_me should not generate a new token if using salt' do
user = create_user
user.expects(:valid?).never
user.remember_me!
assert user.remember_created_at
end
test 'remember_me should not generate a new token if valid token exists' do
user = create_user
user.singleton_class.send(:attr_accessor, :remember_token)
User.to_adapter.expects(:find_first).returns(nil)
user.remember_me!
existing_token = user.remember_token
user.remember_me!
assert_equal existing_token, user.remember_token
end
test 'forget_me should not clear remember token if using salt' do
user = create_user
user.remember_me!
user.expects(:valid?).never
user.forget_me!
end
test 'can generate remember token' do
user = create_user
user.singleton_class.send(:attr_accessor, :remember_token)
User.to_adapter.expects(:find_first).returns(nil)
user.remember_me!
assert user.remember_token
end
test 'serialize into cookie' do
user = create_user
user.remember_me!
id, token, date = User.serialize_into_cookie(user)
assert_equal id, user.to_key
assert_equal token, user.authenticatable_salt
assert date.is_a?(String)
end
test 'serialize from cookie' do
user = create_user
user.remember_me!
assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc)
end
test 'serialize from cookie should accept a String with the datetime seconds and microseconds' do
user = create_user
user.remember_me!
assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc.to_f.to_json)
end
test 'serialize from cookie should return nil with invalid datetime' do
user = create_user
user.remember_me!
assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, "2013")
end
test 'serialize from cookie should return nil if no resource is found' do
assert_nil resource_class.serialize_from_cookie([0], "123", Time.now.utc)
end
test 'serialize from cookie should return nil if no timestamp' do
user = create_user
user.remember_me!
assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt)
end
test 'serialize from cookie should return nil if timestamp is earlier than token creation' do
user = create_user
user.remember_me!
assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 1.day.ago)
end
test 'serialize from cookie should return nil if timestamp is older than remember_for' do
user = create_user
user.remember_created_at = 1.month.ago
user.remember_me!
assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 3.weeks.ago)
end
test 'serialize from cookie me return nil if is a valid resource with invalid token' do
user = create_user
user.remember_me!
assert_nil User.serialize_from_cookie(user.to_key, "123", Time.now.utc)
end
test 'raises a RuntimeError if the user does not implements a rememberable value' do
user = User.new
assert_raise(RuntimeError) { user.rememberable_value }
user_with_remember_token = User.new
def user_with_remember_token.remember_token; '123-token'; end
assert_equal '123-token', user_with_remember_token.rememberable_value
user_with_salt = User.new
def user_with_salt.authenticatable_salt; '123-salt'; end
assert_equal '123-salt', user_with_salt.rememberable_value
end
test 'raises a RuntimeError if authenticatable_salt is nil or empty' do
user = User.new
def user.authenticatable_salt; nil; end
assert_raise RuntimeError do
user.rememberable_value
end
user = User.new
def user.authenticatable_salt; ""; end
assert_raise RuntimeError do
user.rememberable_value
end
end
test 'should respond to remember_me attribute' do
assert_respond_to resource_class.new, :remember_me
assert_respond_to resource_class.new, :remember_me=
end
test 'forget_me should clear remember_created_at if expire_all_remember_me_on_sign_out is true' do
swap Devise, expire_all_remember_me_on_sign_out: true do
resource = create_resource
resource.remember_me!
assert_not_nil resource.remember_created_at
resource.forget_me!
assert_nil resource.remember_created_at
end
end
test 'forget_me should not clear remember_created_at if expire_all_remember_me_on_sign_out is false' do
swap Devise, expire_all_remember_me_on_sign_out: false do
resource = create_resource
resource.remember_me!
assert_not_nil resource.remember_created_at
resource.forget_me!
assert_not_nil resource.remember_created_at
end
end
test 'forget_me should not try to update resource if it has been destroyed' do
resource = create_resource
resource.expects(:remember_created_at).never
resource.expects(:save).never
resource.destroy
resource.forget_me!
end
test 'remember expires at uses remember for configuration' do
swap Devise, remember_for: 3.days do
resource = create_resource
resource.remember_me!
assert_equal 3.days.from_now.to_date, resource.remember_expires_at.to_date
Devise.remember_for = 5.days
assert_equal 5.days.from_now.to_date, resource.remember_expires_at.to_date
end
end
test 'should have the required_fields array' do
assert_equal [
:remember_created_at
], Devise::Models::Rememberable.required_fields(User)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/authenticatable_test.rb | test/models/authenticatable_test.rb | # frozen_string_literal: true
require 'test_helper'
class AuthenticatableTest < ActiveSupport::TestCase
test 'required_fields should be an empty array' do
assert_equal [], Devise::Models::Validatable.required_fields(User)
end
test 'find_first_by_auth_conditions allows custom filtering parameters' do
user = User.create!(email: "example@example.com", password: "1234567")
assert_equal user, User.find_first_by_auth_conditions({ email: "example@example.com" })
assert_nil User.find_first_by_auth_conditions({ email: "example@example.com" }, id: user.id.to_s.next)
end
# assumes default configuration of
# config.case_insensitive_keys = [:email]
# config.strip_whitespace_keys = [:email]
test 'find_or_initialize_with_errors uses parameter filter on find' do
user = User.create!(email: "example@example.com", password: "1234567")
assert_equal user, User.find_or_initialize_with_errors([:email], { email: " EXAMPLE@example.com " })
end
# assumes default configuration of
# config.case_insensitive_keys = [:email]
# config.strip_whitespace_keys = [:email]
test 'find_or_initialize_with_errors uses parameter filter on initialize' do
assert_equal "example@example.com", User.find_or_initialize_with_errors([:email], { email: " EXAMPLE@example.com " }).email
end
test 'find_or_initialize_with_errors adds blank error' do
user_with_error = User.find_or_initialize_with_errors([:email], { email: "" })
assert user_with_error.errors.added?(:email, :blank)
end
test 'find_or_initialize_with_errors adds invalid error' do
user_with_error = User.find_or_initialize_with_errors([:email], { email: "example@example.com" })
assert user_with_error.errors.added?(:email, :invalid)
end
if defined?(ActionController::Parameters)
test 'does not passes an ActionController::Parameters to find_first_by_auth_conditions through find_or_initialize_with_errors' do
user = create_user(email: 'example@example.com')
attributes = ActionController::Parameters.new(email: 'example@example.com')
User.expects(:find_first_by_auth_conditions).with({ 'email' => 'example@example.com' }).returns(user)
User.find_or_initialize_with_errors([:email], attributes)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/confirmable_test.rb | test/models/confirmable_test.rb | # frozen_string_literal: true
require 'test_helper'
class ConfirmableTest < ActiveSupport::TestCase
def setup
setup_mailer
end
test 'should set callbacks to send the mail' do
if DEVISE_ORM == :active_record
defined_callbacks = User._commit_callbacks.map(&:filter)
assert_includes defined_callbacks, :send_on_create_confirmation_instructions
assert_includes defined_callbacks, :send_reconfirmation_instructions
elsif DEVISE_ORM == :mongoid
assert_includes User._create_callbacks.map(&:filter), :send_on_create_confirmation_instructions
assert_includes User._update_callbacks.map(&:filter), :send_reconfirmation_instructions
end
end
test 'should generate confirmation token after creating a record' do
assert_nil new_user.confirmation_token
assert_not_nil create_user.confirmation_token
end
test 'should never generate the same confirmation token for different users' do
confirmation_tokens = []
3.times do
token = create_user.confirmation_token
assert_not_includes confirmation_tokens, token
confirmation_tokens << token
end
end
test 'should confirm a user by updating confirmed at' do
user = create_user
assert_nil user.confirmed_at
assert user.confirm
assert_not_nil user.confirmed_at
end
test 'should verify whether a user is confirmed or not' do
assert_not new_user.confirmed?
user = create_user
assert_not user.confirmed?
user.confirm
assert user.confirmed?
end
test 'should not confirm a user already confirmed' do
user = create_user
assert user.confirm
assert_blank user.errors[:email]
assert_not user.confirm
assert_equal "was already confirmed, please try signing in", user.errors[:email].join
end
test 'should find and confirm a user automatically based on the raw token' do
user = create_user
raw = user.raw_confirmation_token
confirmed_user = User.confirm_by_token(raw)
assert_equal user, confirmed_user
assert user.reload.confirmed?
end
test 'should return a new record with errors when a invalid token is given' do
confirmed_user = User.confirm_by_token('invalid_confirmation_token')
assert_not confirmed_user.persisted?
assert_equal "is invalid", confirmed_user.errors[:confirmation_token].join
end
test 'should return a new record with errors when a blank token is given' do
confirmed_user = User.confirm_by_token('')
assert_not confirmed_user.persisted?
assert confirmed_user.errors.added?(:confirmation_token, :blank)
end
test 'should return a new record with errors when a blank token is given and a record exists on the database' do
user = create_user(confirmation_token: '')
confirmed_user = User.confirm_by_token('')
assert_not user.reload.confirmed?
assert confirmed_user.errors.added?(:confirmation_token, :blank)
end
test 'should return a new record with errors when a nil token is given and a record exists on the database' do
user = create_user(confirmation_token: nil)
confirmed_user = User.confirm_by_token(nil)
assert_not user.reload.confirmed?
assert confirmed_user.errors.added?(:confirmation_token, :blank)
end
test 'should generate errors for a user email if user is already confirmed' do
user = create_user
user.confirmed_at = Time.now
user.save
confirmed_user = User.confirm_by_token(user.raw_confirmation_token)
assert confirmed_user.confirmed?
assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join
end
test 'should show error when a token has already been used' do
user = create_user
raw = user.raw_confirmation_token
User.confirm_by_token(raw)
assert user.reload.confirmed?
confirmed_user = User.confirm_by_token(raw)
assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join
end
test 'should send confirmation instructions by email' do
assert_email_sent "mynewuser@example.com" do
create_user email: "mynewuser@example.com"
end
end
test 'should not send confirmation when trying to save an invalid user' do
assert_email_not_sent do
user = new_user
user.stubs(:valid?).returns(false)
user.save
end
end
test 'should not generate a new token neither send e-mail if skip_confirmation! is invoked' do
user = new_user
user.skip_confirmation!
assert_email_not_sent do
user.save!
assert_nil user.confirmation_token
assert_not_nil user.confirmed_at
end
end
test 'should skip confirmation e-mail without confirming if skip_confirmation_notification! is invoked' do
user = new_user
user.skip_confirmation_notification!
assert_email_not_sent do
user.save!
assert_not user.confirmed?
end
end
test 'should not send confirmation when no email is provided' do
assert_email_not_sent do
user = new_user
user.email = ''
user.save(validate: false)
end
end
test 'should find a user to send confirmation instructions' do
user = create_user
confirmation_user = User.send_confirmation_instructions(email: user.email)
assert_equal user, confirmation_user
end
test 'should return a new user if no email was found' do
confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com")
assert_not confirmation_user.persisted?
end
test 'should add error to new user email if no email was found' do
confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com")
assert confirmation_user.errors[:email]
assert_equal "not found", confirmation_user.errors[:email].join
end
test 'should send email instructions for the user confirm its email' do
user = create_user
assert_email_sent user.email do
User.send_confirmation_instructions(email: user.email)
end
end
test 'should always have confirmation token when email is sent' do
user = new_user
user.instance_eval { def confirmation_required?; false end }
user.save
user.send_confirmation_instructions
assert_not_nil user.reload.confirmation_token
end
test 'should not resend email instructions if the user change their email' do
user = create_user
user.email = 'new_test@example.com'
assert_email_not_sent do
user.save!
end
end
test 'should not reset confirmation status or token when updating email' do
user = create_user
original_token = user.confirmation_token
user.confirm
user.email = 'new_test@example.com'
user.save!
user.reload
assert user.confirmed?
assert_equal original_token, user.confirmation_token
end
test 'should not be able to send instructions if the user is already confirmed' do
user = create_user
user.confirm
assert_not user.resend_confirmation_instructions
assert user.confirmed?
assert_equal 'was already confirmed, please try signing in', user.errors[:email].join
end
test 'confirm time should fallback to devise confirm in default configuration' do
swap Devise, allow_unconfirmed_access_for: 1.day do
user = create_user
user.confirmation_sent_at = 2.days.ago
assert_not user.active_for_authentication?
Devise.allow_unconfirmed_access_for = 3.days
assert user.active_for_authentication?
end
end
test 'should be active when confirmation sent at is not overpast' do
swap Devise, allow_unconfirmed_access_for: 5.days do
Devise.allow_unconfirmed_access_for = 5.days
user = create_user
user.confirmation_sent_at = 4.days.ago
assert user.active_for_authentication?
user.confirmation_sent_at = 5.days.ago
assert_not user.active_for_authentication?
end
end
test 'should be active when already confirmed' do
user = create_user
assert_not user.confirmed?
assert_not user.active_for_authentication?
user.confirm
assert user.confirmed?
assert user.active_for_authentication?
end
test 'should not be active when confirm in is zero' do
Devise.allow_unconfirmed_access_for = 0.days
user = create_user
user.confirmation_sent_at = Time.zone.today
assert_not user.active_for_authentication?
end
test 'should not be active when confirm period is set to 0 days' do
Devise.allow_unconfirmed_access_for = 0.days
user = create_user
Timecop.freeze(Time.zone.today) do
user.confirmation_sent_at = Time.zone.today
assert_not user.active_for_authentication?
end
end
test 'should be active when we set allow_unconfirmed_access_for to nil' do
swap Devise, allow_unconfirmed_access_for: nil do
user = create_user
user.confirmation_sent_at = Time.zone.today
assert user.active_for_authentication?
end
end
test 'should not be active without confirmation' do
user = create_user
user.confirmation_sent_at = nil
user.save
assert_not user.reload.active_for_authentication?
end
test 'should be active without confirmation when confirmation is not required' do
user = create_user
user.instance_eval { def confirmation_required?; false end }
user.confirmation_sent_at = nil
user.save
assert user.reload.active_for_authentication?
end
test 'should not break when a user tries to reset their password in the case where confirmation is not required and confirm_within is set' do
swap Devise, confirm_within: 3.days do
user = create_user
user.instance_eval { def confirmation_required?; false end }
user.confirmation_sent_at = nil
user.save
assert user.reload.confirm
end
end
test 'should find a user to send email instructions for the user confirm its email by authentication_keys' do
swap Devise, authentication_keys: [:username, :email] do
user = create_user
confirm_user = User.send_confirmation_instructions(email: user.email, username: user.username)
assert_equal user, confirm_user
end
end
test 'should require all confirmation_keys' do
swap Devise, confirmation_keys: [:username, :email] do
user = create_user
confirm_user = User.send_confirmation_instructions(email: user.email)
assert_not confirm_user.persisted?
assert confirm_user.errors.added?(:username, :blank)
end
end
def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at)
user = create_user
user.update_attribute(:confirmation_sent_at, confirmation_sent_at)
confirmed_user = User.confirm_by_token(user.raw_confirmation_token)
assert_equal user, confirmed_user
user.reload.confirmed?
end
test 'should accept confirmation email token even after 5 years when no expiration is set' do
assert confirm_user_by_token_with_confirmation_sent_at(5.years.ago)
end
test 'should accept confirmation email token after 2 days when expiration is set to 3 days' do
swap Devise, confirm_within: 3.days do
assert confirm_user_by_token_with_confirmation_sent_at(2.days.ago)
end
end
test 'should not accept confirmation email token after 4 days when expiration is set to 3 days' do
swap Devise, confirm_within: 3.days do
assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago)
end
end
test 'do not generate a new token on resend' do
user = create_user
old = user.confirmation_token
user = User.find(user.id)
user.resend_confirmation_instructions
assert_equal user.confirmation_token, old
end
test 'generate a new token after first has expired' do
swap Devise, confirm_within: 3.days do
user = create_user
old = user.confirmation_token
user.update_attribute(:confirmation_sent_at, 4.days.ago)
user = User.find(user.id)
user.resend_confirmation_instructions
assert_not_equal user.confirmation_token, old
end
end
test 'should call after_confirmation if confirmed' do
user = create_user
user.define_singleton_method :after_confirmation do
self.username = self.username.to_s + 'updated'
end
old = user.username
assert user.confirm
assert_not_equal user.username, old
end
test 'should not call after_confirmation if not confirmed' do
user = create_user
assert user.confirm
user.define_singleton_method :after_confirmation do
self.username = self.username.to_s + 'updated'
end
old = user.username
assert_not user.confirm
assert_equal user.username, old
end
test 'should always perform validations upon confirm when ensure valid true' do
admin = create_admin
admin.stubs(:valid?).returns(false)
assert_not admin.confirm(ensure_valid: true)
end
end
class ReconfirmableTest < ActiveSupport::TestCase
test 'should not worry about validations on confirm even with reconfirmable' do
admin = create_admin
admin.reset_password_token = "a"
assert admin.confirm
end
test 'should generate confirmation token after changing email' do
admin = create_admin
assert admin.confirm
residual_token = admin.confirmation_token
assert admin.update(email: 'new_test@example.com')
assert_not_equal residual_token, admin.confirmation_token
end
test 'should not regenerate confirmation token or require reconfirmation if skipping reconfirmation after changing email' do
admin = create_admin
original_token = admin.confirmation_token
assert admin.confirm
admin.skip_reconfirmation!
assert admin.update(email: 'new_test@example.com')
assert admin.confirmed?
assert_not admin.pending_reconfirmation?
assert_equal original_token, admin.confirmation_token
end
test 'should skip sending reconfirmation email when email is changed and skip_confirmation_notification! is invoked' do
admin = create_admin
admin.skip_confirmation_notification!
assert_email_not_sent do
admin.update(email: 'new_test@example.com')
end
end
test 'should regenerate confirmation token after changing email' do
admin = create_admin
assert admin.confirm
assert admin.update(email: 'old_test@example.com')
token = admin.confirmation_token
assert admin.update(email: 'new_test@example.com')
assert_not_equal token, admin.confirmation_token
end
test 'should send confirmation instructions by email after changing email' do
admin = create_admin
assert admin.confirm
assert_email_sent "new_test@example.com" do
assert admin.update(email: 'new_test@example.com')
end
assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded
end
test 'should send confirmation instructions by email after changing email from nil' do
admin = create_admin(email: nil)
assert_email_sent "new_test@example.com" do
assert admin.update(email: 'new_test@example.com')
end
assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded
end
test 'should not send confirmation by email after changing password' do
admin = create_admin
assert admin.confirm
assert_email_not_sent do
assert admin.update(password: 'newpass', password_confirmation: 'newpass')
end
end
test 'should not send confirmation by email after changing to a blank email' do
admin = create_admin
assert admin.confirm
assert_email_not_sent do
admin.email = ''
admin.save(validate: false)
end
end
test 'should stay confirmed when email is changed' do
admin = create_admin
assert admin.confirm
assert admin.update(email: 'new_test@example.com')
assert admin.confirmed?
end
test 'should update email only when it is confirmed' do
admin = create_admin
assert admin.confirm
assert admin.update(email: 'new_test@example.com')
assert_not_equal 'new_test@example.com', admin.email
assert admin.confirm
assert_equal 'new_test@example.com', admin.email
end
test 'should not allow admin to get past confirmation email by resubmitting their new address' do
admin = create_admin
assert admin.confirm
assert admin.update(email: 'new_test@example.com')
assert_not_equal 'new_test@example.com', admin.email
assert admin.update(email: 'new_test@example.com')
assert_not_equal 'new_test@example.com', admin.email
end
test 'should find a admin by send confirmation instructions with unconfirmed_email' do
admin = create_admin
assert admin.confirm
assert admin.update(email: 'new_test@example.com')
confirmation_admin = Admin.send_confirmation_instructions(email: admin.unconfirmed_email)
assert_equal admin, confirmation_admin
end
test 'should return a new admin if no email or unconfirmed_email was found' do
confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com")
assert_not confirmation_admin.persisted?
end
test 'should add error to new admin email if no email or unconfirmed_email was found' do
confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com")
assert confirmation_admin.errors[:email]
assert_equal "not found", confirmation_admin.errors[:email].join
end
test 'should find admin with email in unconfirmed_emails' do
admin = create_admin
admin.unconfirmed_email = "new_test@email.com"
assert admin.save
admin = Admin.find_by_unconfirmed_email_with_errors(email: "new_test@email.com")
assert admin.persisted?
end
test 'required_fields should contain the fields that Devise uses' do
assert_equal [
:confirmation_token,
:confirmed_at,
:confirmation_sent_at
], Devise::Models::Confirmable.required_fields(User)
end
test 'required_fields should also contain unconfirmable when reconfirmable_email is true' do
assert_equal [
:confirmation_token,
:confirmed_at,
:confirmation_sent_at,
:unconfirmed_email
], Devise::Models::Confirmable.required_fields(Admin)
end
test 'should not require reconfirmation after creating a record' do
admin = create_admin
assert_not admin.pending_reconfirmation?
end
test 'should not require reconfirmation after creating a record with #save called in callback' do
class Admin::WithSaveInCallback < Admin
after_create :save
end
admin = Admin::WithSaveInCallback.create(valid_attributes.except(:username))
assert_not admin.pending_reconfirmation?
end
test 'should require reconfirmation after creating a record and updating the email' do
admin = create_admin
assert_not admin.instance_variable_get(:@bypass_confirmation_postpone)
admin.email = "new_test@email.com"
admin.save
assert admin.pending_reconfirmation?
end
test 'should notify previous email on email change when configured' do
swap Devise, send_email_changed_notification: true do
admin = create_admin
original_email = admin.email
assert_difference 'ActionMailer::Base.deliveries.size', 2 do
assert admin.update(email: 'new-email@example.com')
end
assert_equal original_email, ActionMailer::Base.deliveries[-2]['to'].to_s
assert_equal 'new-email@example.com', ActionMailer::Base.deliveries[-1]['to'].to_s
assert_email_not_sent do
assert admin.confirm
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/models/recoverable_test.rb | test/models/recoverable_test.rb | # frozen_string_literal: true
require 'test_helper'
class RecoverableTest < ActiveSupport::TestCase
def setup
setup_mailer
end
test 'should not generate reset password token after creating a record' do
assert_nil new_user.reset_password_token
end
test 'should never generate the same reset password token for different users' do
reset_password_tokens = []
3.times do
user = create_user
user.send_reset_password_instructions
token = user.reset_password_token
assert_not_includes reset_password_tokens, token
reset_password_tokens << token
end
end
test 'should reset password and password confirmation from params' do
user = create_user
user.reset_password('123456789', '987654321')
assert_equal '123456789', user.password
assert_equal '987654321', user.password_confirmation
end
test 'should reset password and save the record' do
assert create_user.reset_password('123456789', '123456789')
end
test 'should clear reset password token while resetting the password' do
user = create_user
assert_nil user.reset_password_token
user.send_reset_password_instructions
assert_present user.reset_password_token
assert user.reset_password('123456789', '123456789')
assert_nil user.reset_password_token
end
test 'should not clear reset password token for new user' do
user = new_user
assert_nil user.reset_password_token
user.send_reset_password_instructions
assert_present user.reset_password_token
user.save
assert_present user.reset_password_token
end
test 'should clear reset password token if changing password' do
user = create_user
assert_nil user.reset_password_token
user.send_reset_password_instructions
assert_present user.reset_password_token
user.password = "123456678"
user.password_confirmation = "123456678"
user.save!
assert_nil user.reset_password_token
end
test 'should clear reset password token if changing email' do
user = create_user
assert_nil user.reset_password_token
user.send_reset_password_instructions
assert_present user.reset_password_token
user.email = "another@example.com"
user.save!
assert_nil user.reset_password_token
end
test 'should clear reset password successfully even if there is no email' do
user = create_user_without_email
assert_nil user.reset_password_token
user.send_reset_password_instructions
assert_present user.reset_password_token
user.password = "123456678"
user.password_confirmation = "123456678"
user.save!
assert_nil user.reset_password_token
end
test 'should not clear reset password token if record is invalid' do
user = create_user
user.send_reset_password_instructions
assert_present user.reset_password_token
assert_not user.reset_password('123456789', '987654321')
assert_present user.reset_password_token
end
test 'should not reset password with invalid data' do
user = create_user
user.stubs(:valid?).returns(false)
assert_not user.reset_password('123456789', '987654321')
end
test 'should reset reset password token and send instructions by email' do
user = create_user
assert_email_sent do
token = user.reset_password_token
user.send_reset_password_instructions
assert_not_equal token, user.reset_password_token
end
end
test 'should find a user to send instructions by email' do
user = create_user
reset_password_user = User.send_reset_password_instructions(email: user.email)
assert_equal user, reset_password_user
end
test 'should return a new record with errors if user was not found by e-mail' do
reset_password_user = User.send_reset_password_instructions(email: "invalid@example.com")
assert_not reset_password_user.persisted?
assert_equal "not found", reset_password_user.errors[:email].join
end
test 'should find a user to send instructions by authentication_keys' do
swap Devise, authentication_keys: [:username, :email] do
user = create_user
reset_password_user = User.send_reset_password_instructions(email: user.email, username: user.username)
assert_equal user, reset_password_user
end
end
test 'should require all reset_password_keys' do
swap Devise, reset_password_keys: [:username, :email] do
user = create_user
reset_password_user = User.send_reset_password_instructions(email: user.email)
assert_not reset_password_user.persisted?
assert reset_password_user.errors.added?(:username, :blank)
end
end
test 'should reset reset_password_token before send the reset instructions email' do
user = create_user
token = user.reset_password_token
User.send_reset_password_instructions(email: user.email)
assert_not_equal token, user.reload.reset_password_token
end
test 'should send email instructions to the user reset their password' do
user = create_user
assert_email_sent do
User.send_reset_password_instructions(email: user.email)
end
end
test 'should find a user to reset their password based on the raw token' do
user = create_user
raw = user.send_reset_password_instructions
reset_password_user = User.reset_password_by_token(reset_password_token: raw)
assert_equal user, reset_password_user
end
test 'should return a new record with errors if no reset_password_token is found' do
reset_password_user = User.reset_password_by_token(reset_password_token: 'invalid_token')
assert_not reset_password_user.persisted?
assert_equal "is invalid", reset_password_user.errors[:reset_password_token].join
end
test 'should return a new record with errors if reset_password_token is blank' do
reset_password_user = User.reset_password_by_token(reset_password_token: '')
assert_not reset_password_user.persisted?
assert reset_password_user.errors.added?(:reset_password_token, :blank)
end
test 'should return a new record with errors if password is blank' do
user = create_user
raw = user.send_reset_password_instructions
reset_password_user = User.reset_password_by_token(reset_password_token: raw, password: '')
assert_not reset_password_user.errors.empty?
assert reset_password_user.errors.added?(:password, :blank)
assert_equal raw, reset_password_user.reset_password_token
end
test 'should return a new record with errors if password is not provided' do
user = create_user
raw = user.send_reset_password_instructions
reset_password_user = User.reset_password_by_token(reset_password_token: raw)
assert_not reset_password_user.errors.empty?
assert reset_password_user.errors.added?(:password, :blank)
assert_equal raw, reset_password_user.reset_password_token
end
test 'should reset successfully user password given the new password and confirmation' do
user = create_user
old_password = user.password
raw = user.send_reset_password_instructions
reset_password_user = User.reset_password_by_token(
reset_password_token: raw,
password: 'new_password',
password_confirmation: 'new_password'
)
assert_nil reset_password_user.reset_password_token
user.reload
assert_not user.valid_password?(old_password)
assert user.valid_password?('new_password')
assert_nil user.reset_password_token
end
test 'should not reset password after reset_password_within time' do
swap Devise, reset_password_within: 1.hour do
user = create_user
raw = user.send_reset_password_instructions
old_password = user.password
user.reset_password_sent_at = 2.days.ago
user.save!
reset_password_user = User.reset_password_by_token(
reset_password_token: raw,
password: 'new_password',
password_confirmation: 'new_password'
)
user.reload
assert user.valid_password?(old_password)
assert_not user.valid_password?('new_password')
assert_equal "has expired, please request a new one", reset_password_user.errors[:reset_password_token].join
end
end
test 'required_fields should contain the fields that Devise uses' do
assert_equal [
:reset_password_sent_at,
:reset_password_token
], Devise::Models::Recoverable.required_fields(User)
end
test 'should return a user based on the raw token' do
user = create_user
raw = user.send_reset_password_instructions
assert_equal user, User.with_reset_password_token(raw)
end
test 'should return the same reset password token as generated' do
user = create_user
raw = user.send_reset_password_instructions
assert_equal user.reset_password_token, Devise.token_generator.digest(self.class, :reset_password_token, raw)
end
test 'should return nil if a user based on the raw token is not found' do
assert_nil User.with_reset_password_token('random-token')
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/active_record_generator_test.rb | test/generators/active_record_generator_test.rb | # frozen_string_literal: true
require "test_helper"
if DEVISE_ORM == :active_record
require "generators/active_record/devise_generator"
class ActiveRecordGeneratorTest < Rails::Generators::TestCase
tests ActiveRecord::Generators::DeviseGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "all files are properly created with rails31 migration syntax" do
run_generator %w(monster)
assert_migration "db/migrate/devise_create_monsters.rb", /def change/
end
test "all files are properly created with changed db/migrate path in application configuration" do
old_paths = Rails.application.config.paths["db/migrate"]
Rails.application.config.paths.add "db/migrate", with: "db2/migrate"
run_generator %w(monster)
assert_migration "db2/migrate/devise_create_monsters.rb", /def change/
Rails.application.config.paths["db/migrate"] = old_paths
end
test "all files for namespaced model are properly created" do
run_generator %w(admin/monster)
assert_migration "db/migrate/devise_create_admin_monsters.rb", /def change/
end
test "update model migration when model exists" do
run_generator %w(monster)
assert_file "app/models/monster.rb"
run_generator %w(monster)
assert_migration "db/migrate/add_devise_to_monsters.rb"
end
test "update model migration when model exists with changed db/migrate path in application configuration" do
old_paths = Rails.application.config.paths["db/migrate"]
Rails.application.config.paths.add "db/migrate", with: "db2/migrate"
run_generator %w(monster)
assert_file "app/models/monster.rb"
run_generator %w(monster)
assert_migration "db2/migrate/add_devise_to_monsters.rb"
Rails.application.config.paths["db/migrate"] = old_paths
end
test "all files are properly deleted" do
run_generator %w(monster)
run_generator %w(monster)
assert_migration "db/migrate/devise_create_monsters.rb"
assert_migration "db/migrate/add_devise_to_monsters.rb"
run_generator %w(monster), behavior: :revoke
assert_no_migration "db/migrate/add_devise_to_monsters.rb"
assert_migration "db/migrate/devise_create_monsters.rb"
run_generator %w(monster), behavior: :revoke
assert_no_file "app/models/monster.rb"
assert_no_migration "db/migrate/devise_create_monsters.rb"
end
test "use string column type for ip addresses" do
run_generator %w(monster)
assert_migration "db/migrate/devise_create_monsters.rb", /t.string :current_sign_in_ip/
assert_migration "db/migrate/devise_create_monsters.rb", /t.string :last_sign_in_ip/
end
test "do NOT add primary key type when NOT specified in rails generator" do
run_generator %w(monster)
assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters do/
end
test "add primary key type with rails 5 when specified in rails generator" do
run_generator ["monster", "--primary_key_type=uuid"]
assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters, id: :uuid do/
end
end
module RailsEngine
class Engine < Rails::Engine
isolate_namespace RailsEngine
end
end
def simulate_inside_engine(engine, namespace)
if Rails::Generators.respond_to?(:namespace=)
swap Rails::Generators, namespace: namespace do
yield
end
else
swap Rails, application: engine.instance do
yield
end
end
end
class ActiveRecordEngineGeneratorTest < Rails::Generators::TestCase
tests ActiveRecord::Generators::DeviseGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "all files are properly created in rails 4.0" do
simulate_inside_engine(RailsEngine::Engine, RailsEngine) do
run_generator ["monster"]
assert_file "app/models/rails_engine/monster.rb", /devise/
assert_file "app/models/rails_engine/monster.rb" do |content|
assert_no_match %r{attr_accessible :email}, content
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/devise_generator_test.rb | test/generators/devise_generator_test.rb | # frozen_string_literal: true
require 'test_helper'
require "generators/devise/devise_generator"
class DeviseGeneratorTest < Rails::Generators::TestCase
tests Devise::Generators::DeviseGenerator
destination File.expand_path("../../tmp", __FILE__)
setup do
prepare_destination
copy_routes
end
test "route generation for simple model names" do
run_generator %w(monster name:string)
assert_file "config/routes.rb", /devise_for :monsters/
end
test "route generation for namespaced model names" do
run_generator %w(monster/goblin name:string)
match = /devise_for :goblins, class_name: "Monster::Goblin"/
assert_file "config/routes.rb", match
end
test "route generation with skip routes" do
run_generator %w(monster name:string --skip-routes)
match = /devise_for :monsters, skip: :all/
assert_file "config/routes.rb", match
end
def copy_routes
routes = File.expand_path("../../rails_app/config/routes.rb", __FILE__)
destination = File.join(destination_root, "config")
FileUtils.mkdir_p(destination)
FileUtils.cp routes, destination
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/install_generator_test.rb | test/generators/install_generator_test.rb | # frozen_string_literal: true
require "test_helper"
class InstallGeneratorTest < Rails::Generators::TestCase
tests Devise::Generators::InstallGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "assert all files are properly created" do
run_generator(["--orm=active_record"])
assert_file "config/initializers/devise.rb", /devise\/orm\/active_record/
assert_file "config/locales/devise.en.yml"
end
test "fails if no ORM is specified" do
stderr = capture(:stderr) do
run_generator
end
assert_match %r{An ORM must be set to install Devise}, stderr
assert_no_file "config/initializers/devise.rb"
assert_no_file "config/locales/devise.en.yml"
end
test "responder error_status based on rack version" do
run_generator(["--orm=active_record"])
error_status = Rack::RELEASE >= "3.1" ? :unprocessable_content : :unprocessable_entity
assert_file "config/initializers/devise.rb", /config\.responder\.error_status = #{error_status.inspect}/
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/views_generator_test.rb | test/generators/views_generator_test.rb | # frozen_string_literal: true
require "test_helper"
class ViewsGeneratorTest < Rails::Generators::TestCase
tests Devise::Generators::ViewsGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "Assert all views are properly created with no params" do
run_generator
assert_files
assert_shared_links
assert_error_messages
end
test "Assert all views are properly created with scope param" do
run_generator %w(users)
assert_files "users"
assert_shared_links "users"
assert_error_messages "users"
run_generator %w(admins)
assert_files "admins"
assert_shared_links "admins"
assert_error_messages "admins"
end
test "Assert views with simple form" do
run_generator %w(-b simple_form_for)
assert_files
assert_file "app/views/devise/confirmations/new.html.erb", /simple_form_for/
run_generator %w(users -b simple_form_for)
assert_files "users"
assert_file "app/views/users/confirmations/new.html.erb", /simple_form_for/
end
test "Assert views with markerb" do
run_generator %w(--markerb)
assert_files nil, mail_template_engine: "markerb"
end
test "Assert only views within specified directories" do
run_generator %w(-v sessions registrations)
assert_file "app/views/devise/sessions/new.html.erb"
assert_file "app/views/devise/registrations/new.html.erb"
assert_file "app/views/devise/registrations/edit.html.erb"
assert_no_file "app/views/devise/confirmations/new.html.erb"
assert_no_file "app/views/devise/mailer/confirmation_instructions.html.erb"
end
test "Assert mailer specific directory with simple form" do
run_generator %w(-v mailer -b simple_form_for)
assert_file "app/views/devise/mailer/confirmation_instructions.html.erb"
assert_file "app/views/devise/mailer/reset_password_instructions.html.erb"
assert_file "app/views/devise/mailer/unlock_instructions.html.erb"
end
test "Assert specified directories with scope" do
run_generator %w(users -v sessions)
assert_file "app/views/users/sessions/new.html.erb"
assert_no_file "app/views/users/confirmations/new.html.erb"
end
test "Assert specified directories with simple form" do
run_generator %w(-v registrations -b simple_form_for)
assert_file "app/views/devise/registrations/new.html.erb", /simple_form_for/
assert_no_file "app/views/devise/confirmations/new.html.erb"
end
test "Assert specified directories with markerb" do
run_generator %w(--markerb -v passwords mailer)
assert_file "app/views/devise/passwords/new.html.erb"
assert_no_file "app/views/devise/confirmations/new.html.erb"
assert_file "app/views/devise/mailer/reset_password_instructions.markerb"
end
def assert_files(scope = nil, options = {})
scope = "devise" if scope.nil?
mail_template_engine = options[:mail_template_engine] || "html.erb"
assert_file "app/views/#{scope}/confirmations/new.html.erb"
assert_file "app/views/#{scope}/mailer/confirmation_instructions.#{mail_template_engine}"
assert_file "app/views/#{scope}/mailer/reset_password_instructions.#{mail_template_engine}"
assert_file "app/views/#{scope}/mailer/unlock_instructions.#{mail_template_engine}"
assert_file "app/views/#{scope}/passwords/edit.html.erb"
assert_file "app/views/#{scope}/passwords/new.html.erb"
assert_file "app/views/#{scope}/registrations/new.html.erb"
assert_file "app/views/#{scope}/registrations/edit.html.erb"
assert_file "app/views/#{scope}/sessions/new.html.erb"
assert_file "app/views/#{scope}/shared/_links.html.erb"
assert_file "app/views/#{scope}/shared/_error_messages.html.erb"
assert_file "app/views/#{scope}/unlocks/new.html.erb"
end
def assert_shared_links(scope = nil)
scope = "devise" if scope.nil?
link = /<%= render \"#{scope}\/shared\/links\" %>/
assert_file "app/views/#{scope}/passwords/edit.html.erb", link
assert_file "app/views/#{scope}/passwords/new.html.erb", link
assert_file "app/views/#{scope}/confirmations/new.html.erb", link
assert_file "app/views/#{scope}/registrations/new.html.erb", link
assert_file "app/views/#{scope}/sessions/new.html.erb", link
assert_file "app/views/#{scope}/unlocks/new.html.erb", link
end
def assert_error_messages(scope = nil)
scope = "devise" if scope.nil?
link = /<%= render \"#{scope}\/shared\/error_messages\", resource: resource %>/
assert_file "app/views/#{scope}/passwords/edit.html.erb", link
assert_file "app/views/#{scope}/passwords/new.html.erb", link
assert_file "app/views/#{scope}/confirmations/new.html.erb", link
assert_file "app/views/#{scope}/registrations/new.html.erb", link
assert_file "app/views/#{scope}/registrations/edit.html.erb", link
assert_file "app/views/#{scope}/unlocks/new.html.erb", link
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/controllers_generator_test.rb | test/generators/controllers_generator_test.rb | # frozen_string_literal: true
require "test_helper"
class ControllersGeneratorTest < Rails::Generators::TestCase
tests Devise::Generators::ControllersGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "Assert no controllers are created with no params" do
capture(:stderr) { run_generator }
assert_no_file "app/controllers/sessions_controller.rb"
assert_no_file "app/controllers/registrations_controller.rb"
assert_no_file "app/controllers/confirmations_controller.rb"
assert_no_file "app/controllers/passwords_controller.rb"
assert_no_file "app/controllers/unlocks_controller.rb"
assert_no_file "app/controllers/omniauth_callbacks_controller.rb"
end
test "Assert all controllers are properly created with scope param" do
run_generator %w(users)
assert_class_names 'users'
run_generator %w(admins)
assert_class_names 'admins'
end
test "Assert specified controllers with scope" do
run_generator %w(users -c sessions)
assert_file "app/controllers/users/sessions_controller.rb"
assert_no_file "app/controllers/users/registrations_controller.rb"
assert_no_file "app/controllers/users/confirmations_controller.rb"
assert_no_file "app/controllers/users/passwords_controller.rb"
assert_no_file "app/controllers/users/unlocks_controller.rb"
assert_no_file "app/controllers/users/omniauth_callbacks_controller.rb"
end
private
def assert_class_names(scope, options = {})
base_dir = "app/controllers#{scope.blank? ? '' : ('/' + scope)}"
scope_prefix = scope.blank? ? '' : (scope.camelize + '::')
controllers = options[:controllers] ||
%w(confirmations passwords registrations sessions unlocks omniauth_callbacks)
controllers.each do |c|
assert_file "#{base_dir}/#{c}_controller.rb", /#{scope_prefix + c.camelize}/
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/generators/mongoid_generator_test.rb | test/generators/mongoid_generator_test.rb | # frozen_string_literal: true
require "test_helper"
if DEVISE_ORM == :mongoid
require "generators/mongoid/devise_generator"
class MongoidGeneratorTest < Rails::Generators::TestCase
tests Mongoid::Generators::DeviseGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "all files are properly created" do
run_generator %w(monster)
assert_file "app/models/monster.rb", /devise/
end
test "all files are properly deleted" do
run_generator %w(monster)
run_generator %w(monster), behavior: :revoke
assert_no_file "app/models/monster.rb"
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/omniauth/config_test.rb | test/omniauth/config_test.rb | # frozen_string_literal: true
require 'test_helper'
class OmniAuthConfigTest < ActiveSupport::TestCase
class MyStrategy
include OmniAuth::Strategy
end
test 'strategy_name returns provider if no options given' do
config = Devise::OmniAuth::Config.new :facebook, [{}]
assert_equal :facebook, config.strategy_name
end
test 'strategy_name returns provider if no name option are given' do
config = Devise::OmniAuth::Config.new :facebook, [{ other: :option }]
assert_equal :facebook, config.strategy_name
end
test 'returns name option when have a name' do
config = Devise::OmniAuth::Config.new :facebook, [{ name: :github }]
assert_equal :github, config.strategy_name
end
test "finds contrib strategies" do
config = Devise::OmniAuth::Config.new :facebook, [{}]
assert_equal OmniAuth::Strategies::Facebook, config.strategy_class
end
class NamedTestStrategy
include OmniAuth::Strategy
option :name, :the_one
end
test "finds the strategy in OmniAuth's list by name" do
config = Devise::OmniAuth::Config.new :the_one, [{}]
assert_equal NamedTestStrategy, config.strategy_class
end
class UnNamedTestStrategy
include OmniAuth::Strategy
end
test "finds the strategy in OmniAuth's list by class name" do
config = Devise::OmniAuth::Config.new :un_named_test_strategy, [{}]
assert_equal UnNamedTestStrategy, config.strategy_class
end
test 'raises an error if strategy cannot be found' do
config = Devise::OmniAuth::Config.new :my_other_strategy, [{}]
assert_raise Devise::OmniAuth::StrategyNotFound do
config.strategy_class
end
end
test 'allows the user to define a custom require path' do
config = Devise::OmniAuth::Config.new :my_strategy, [{strategy_class: MyStrategy}]
config_class = config.strategy_class
assert_equal MyStrategy, config_class
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/omniauth/url_helpers_test.rb | test/omniauth/url_helpers_test.rb | # frozen_string_literal: true
require 'test_helper'
class OmniAuthRoutesTest < ActionController::TestCase
tests ApplicationController
def assert_path(action, provider, with_param = true)
# Resource param
assert_equal @controller.send(action, :user, provider),
@controller.send("user_#{provider}_#{action}")
# With an object
assert_equal @controller.send(action, User.new, provider),
@controller.send("user_#{provider}_#{action}")
if with_param
# Default url params
assert_equal @controller.send(action, :user, provider, param: 123),
@controller.send("user_#{provider}_#{action}", param: 123)
end
end
test 'should alias omniauth_callback to mapped user auth_callback' do
assert_path :omniauth_callback_path, :facebook
end
test 'should alias omniauth_authorize to mapped user auth_authorize' do
assert_path :omniauth_authorize_path, :facebook, false
end
test 'should generate authorization path' do
assert_match "/users/auth/facebook", @controller.omniauth_authorize_path(:user, :facebook)
assert_raise NoMethodError do
@controller.omniauth_authorize_path(:user, :github)
end
end
test 'should generate authorization path for named open_id omniauth' do
assert_match "/users/auth/google", @controller.omniauth_authorize_path(:user, :google)
end
test 'should generate authorization path with params' do
assert_match "/users/auth/openid?openid_url=http%3A%2F%2Fyahoo.com",
@controller.omniauth_authorize_path(:user, :openid, openid_url: "http://yahoo.com")
end
test 'should not add a "?" if no param was sent' do
assert_equal "/users/auth/openid",
@controller.omniauth_authorize_path(:user, :openid)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/orm/active_record.rb | test/orm/active_record.rb | # frozen_string_literal: true
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.logger = Logger.new(nil)
ActiveRecord::Base.include_root_in_json = true
migrate_path = File.expand_path("../../rails_app/db/migrate/", __FILE__)
if Devise::Test.rails71_and_up?
ActiveRecord::MigrationContext.new(migrate_path).migrate
else
ActiveRecord::MigrationContext.new(migrate_path, ActiveRecord::SchemaMigration).migrate
end
class ActiveSupport::TestCase
self.use_transactional_tests = true
self.use_instantiated_fixtures = false
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.