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 |
|---|---|---|---|---|---|---|---|---|
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/dsl_helper.rb | lib/aasm/dsl_helper.rb | module AASM
module DslHelper
class Proxy
attr_accessor :options
def initialize(options, valid_keys, source)
@valid_keys = valid_keys
@source = source
@options = options
end
def method_missing(name, *args, &block)
if @valid_keys.include?(name)
options[name] = Array(options[name])
options[name] << block if block
options[name] += Array(args)
else
@source.send name, *args, &block
end
end
end
def add_options_from_dsl(options, valid_keys, &block)
proxy = Proxy.new(options, valid_keys, self)
proxy.instance_eval(&block)
proxy.options
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest/have_state.rb | lib/aasm/minitest/have_state.rb | module Minitest::Assertions
def assert_have_state(object, state, options = {})
state_machine_name = options.fetch(:on, :default)
assert object.aasm(state_machine_name).current_state == state,
"Expected that :#{object.aasm(state_machine_name).current_state} would be :#{state} (on :#{state_machine_name})"
end
def refute_have_state(object, state, options = {})
state_machine_name = options.fetch(:on, :default)
refute object.aasm(state_machine_name).current_state == state,
"Expected that :#{object.aasm(state_machine_name).current_state} would be :#{state} (on :#{state_machine_name})"
end
end | ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest/allow_event.rb | lib/aasm/minitest/allow_event.rb | module Minitest::Assertions
def assert_event_allowed(object, event, options = {})
state_machine_name = options.fetch(:on, :default)
assert object.aasm(state_machine_name).may_fire_event?(event),
"Expected that the event :#{event} would be allowed (on :#{state_machine_name})"
end
def refute_event_allowed(object, event, options = {})
state_machine_name = options.fetch(:on, :default)
refute object.aasm(state_machine_name).may_fire_event?(event),
"Expected that the event :#{event} would not be allowed (on :#{state_machine_name})"
end
end | ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest/transition_from.rb | lib/aasm/minitest/transition_from.rb | module Minitest::Assertions
def assert_transitions_from(object, from_state, *args)
options = args.first
options[:on] ||= :default
assert _transitions_from?(object, from_state, args, options),
"Expected transition state to :#{options[:to]} from :#{from_state} on event :#{options[:on_event]}, (on :#{options[:on]})"
end
def refute_transitions_from(object, from_state, *args)
options = args.first
options[:on] ||= :default
refute _transitions_from?(object, from_state, args, options),
"Expected transition state to :#{options[:to]} from :#{from_state} on event :#{options[:on_event]}, (on :#{options[:on]})"
end
def _transitions_from?(object, from_state, args, options)
state_machine_name = options[:on]
object.aasm(state_machine_name).current_state = from_state.to_sym
object.send(options[:on_event], *args) && options[:to].to_sym == object.aasm(state_machine_name).current_state
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest/allow_transition_to.rb | lib/aasm/minitest/allow_transition_to.rb | module Minitest::Assertions
def assert_transition_to_allowed(object, to_state, options = {})
state_machine_name = options.fetch(:on, :default)
assert object.aasm(state_machine_name).states(permitted: true).include?(to_state),
"Expected that the state :#{to_state} would be reachable (on :#{state_machine_name})"
end
def refute_transition_to_allowed(object, to_state, options = {})
state_machine_name = options.fetch(:on, :default)
refute object.aasm(state_machine_name).states(permitted: true).include?(to_state),
"Expected that the state :#{to_state} would be reachable (on :#{state_machine_name})"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/rspec/have_state.rb | lib/aasm/rspec/have_state.rb | RSpec::Matchers.define :have_state do |state|
match do |obj|
@state_machine_name ||= :default
obj.aasm(@state_machine_name).current_state == state.to_sym
end
chain :on do |state_machine_name|
@state_machine_name = state_machine_name
end
description do
"have state #{expected} (on :#{@state_machine_name})"
end
failure_message do |obj|
"expected that :#{obj.aasm(@state_machine_name).current_state} would be :#{expected} (on :#{@state_machine_name})"
end
failure_message_when_negated do |obj|
"expected that :#{obj.aasm(@state_machine_name).current_state} would not be :#{expected} (on :#{@state_machine_name})"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/rspec/allow_event.rb | lib/aasm/rspec/allow_event.rb | RSpec::Matchers.define :allow_event do |event|
match do |obj|
@state_machine_name ||= :default
obj.aasm(@state_machine_name).may_fire_event?(event, *@args)
end
chain :on do |state_machine_name|
@state_machine_name = state_machine_name
end
chain :with do |*args|
@args = args
end
description do
"allow event #{expected} (on :#{@state_machine_name})"
end
failure_message do |obj|
"expected that the event :#{expected} would be allowed (on :#{@state_machine_name})"
end
failure_message_when_negated do |obj|
"expected that the event :#{expected} would not be allowed (on :#{@state_machine_name})"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/rspec/transition_from.rb | lib/aasm/rspec/transition_from.rb | RSpec::Matchers.define :transition_from do |from_state|
match do |obj|
@state_machine_name ||= :default
obj.aasm(@state_machine_name).current_state = from_state.to_sym
begin
obj.send(@event, *@args) && obj.aasm(@state_machine_name).current_state == @to_state.to_sym
rescue AASM::InvalidTransition
false
end
end
chain :on do |state_machine_name|
@state_machine_name = state_machine_name
end
chain :to do |state|
@to_state = state
end
chain :on_event do |event, *args|
@event = event
@args = args
end
description do
"transition state to :#{@to_state} from :#{expected} on event :#{@event}, with params: #{@args} (on :#{@state_machine_name})"
end
failure_message do |obj|
"expected that :#{obj.aasm(@state_machine_name).current_state} would be :#{@to_state} (on :#{@state_machine_name})"
end
failure_message_when_negated do |obj|
"expected that :#{obj.aasm(@state_machine_name).current_state} would not be :#{@to_state} (on :#{@state_machine_name})"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/rspec/allow_transition_to.rb | lib/aasm/rspec/allow_transition_to.rb | RSpec::Matchers.define :allow_transition_to do |state|
match do |obj|
@state_machine_name ||= :default
obj.aasm(@state_machine_name).states({:permitted => true}, *@args).include?(state)
end
chain :on do |state_machine_name|
@state_machine_name = state_machine_name
end
chain :with do |*args|
@args = args
end
description do
"allow transition to #{expected} (on :#{@state_machine_name})"
end
failure_message do |obj|
"expected that the state :#{expected} would be reachable (on :#{@state_machine_name})"
end
failure_message_when_negated do |obj|
"expected that the state :#{expected} would not be reachable (on :#{@state_machine_name})"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/orm.rb | lib/aasm/persistence/orm.rb | module AASM
module Persistence
# This module adds transactional support for any database that supports it.
# This includes rollback capability and rollback/commit callbacks.
module ORM
# Writes <tt>state</tt> to the state column and persists it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state, name=:default)
attribute_name = self.class.aasm(name).attribute_name
old_value = aasm_read_attribute(attribute_name)
aasm_write_state_attribute state, name
success = if aasm_skipping_validations(name)
aasm_update_column(attribute_name, aasm_raw_attribute_value(state, name))
else
aasm_save
end
unless success
aasm_rollback(name, old_value)
aasm_raise_invalid_record if aasm_whiny_persistence(name)
end
success
end
# Writes <tt>state</tt> to the state field, but does not persist it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state, name=:default)
aasm_write_state_attribute(state, name)
end
private
# Save the record and return true if it succeeded/false otherwise.
def aasm_save
raise("Define #aasm_save_without_error in the AASM Persistence class.")
end
def aasm_raise_invalid_record
raise("Define #aasm_raise_invalid_record in the AASM Persistence class.")
end
# Update only the column without running validations.
def aasm_update_column(attribute_name, value)
raise("Define #aasm_update_column in the AASM Persistence class.")
end
def aasm_read_attribute(name)
raise("Define #aasm_read_attribute the AASM Persistence class.")
end
def aasm_write_attribute(name, value)
raise("Define #aasm_write_attribute in the AASM Persistence class.")
end
# Returns true or false if transaction completed successfully.
def aasm_transaction(requires_new, requires_lock)
raise("Define #aasm_transaction the AASM Persistence class.")
end
def aasm_supports_transactions?
true
end
def aasm_execute_after_commit
yield
end
def aasm_write_state_attribute(state, name=:default)
aasm_write_attribute(self.class.aasm(name).attribute_name, aasm_raw_attribute_value(state, name))
end
def aasm_raw_attribute_value(state, _name=:default)
state.to_s
end
def aasm_rollback(name, old_value)
aasm_write_attribute(self.class.aasm(name).attribute_name, old_value)
false
end
def aasm_whiny_persistence(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.whiny_persistence
end
def aasm_skipping_validations(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.skip_validation_on_save
end
def use_transactions?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.use_transactions
end
def requires_new?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.requires_new_transaction
end
def requires_lock?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.requires_lock
end
# Returns true if event was fired successfully and transaction completed.
def aasm_fire_event(state_machine_name, name, options, *args, &block)
return super unless aasm_supports_transactions? && options[:persist]
event = self.class.aasm(state_machine_name).state_machine.events[name]
event.fire_callbacks(:before_transaction, self, *args)
event.fire_global_callbacks(:before_all_transactions, self, *args)
begin
success = if options[:persist] && use_transactions?(state_machine_name)
aasm_transaction(requires_new?(state_machine_name), requires_lock?(state_machine_name)) do
super
end
else
super
end
if success && !(event.options.keys & [:after_commit, :after_all_commits]).empty?
aasm_execute_after_commit do
event.fire_callbacks(:after_commit, self, *args)
event.fire_global_callbacks(:after_all_commits, self, *args)
end
end
success
ensure
event.fire_callbacks(:after_transaction, self, *args)
event.fire_global_callbacks(:after_all_transactions, self, *args)
end
end
end # Transactional
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/plain_persistence.rb | lib/aasm/persistence/plain_persistence.rb | module AASM
module Persistence
module PlainPersistence
# may be overwritten by persistence mixins
def aasm_read_state(name=:default)
# all the following lines behave like @current_state ||= aasm(name).enter_initial_state
current = aasm(name).instance_variable_defined?("@current_state_#{name}") &&
aasm(name).instance_variable_get("@current_state_#{name}")
return current if current
aasm(name).instance_variable_set("@current_state_#{name}", aasm(name).enter_initial_state)
end
# may be overwritten by persistence mixins
def aasm_write_state(new_state, name=:default)
true
end
# may be overwritten by persistence mixins
def aasm_write_state_without_persistence(new_state, name=:default)
aasm(name).instance_variable_set("@current_state_#{name}", new_state)
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/active_record_persistence.rb | lib/aasm/persistence/active_record_persistence.rb | require 'aasm/persistence/orm'
module AASM
module Persistence
module ActiveRecordPersistence
# This method:
#
# * extends the model with ClassMethods
# * includes InstanceMethods
#
# Adds
#
# after_initialize :aasm_ensure_initial_state
#
# As a result, it doesn't matter when you define your methods - the following 2 are equivalent
#
# class Foo < ActiveRecord::Base
# def aasm_write_state(state)
# "bar"
# end
# include AASM
# end
#
# class Foo < ActiveRecord::Base
# include AASM
# def aasm_write_state(state)
# "bar"
# end
# end
#
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::ORM)
base.send(:include, AASM::Persistence::ActiveRecordPersistence::InstanceMethods)
base.extend AASM::Persistence::ActiveRecordPersistence::ClassMethods
base.after_initialize :aasm_ensure_initial_state
# ensure state is in the list of states
base.validate :aasm_validate_states
end
module ClassMethods
def aasm_create_scope(state_machine_name, scope_name)
if ActiveRecord::VERSION::MAJOR >= 3
conditions = { aasm(state_machine_name).attribute_name => scope_name.to_s }
class_eval do
scope scope_name, lambda { where(table_name => conditions) }
end
else
conditions = {
table_name => { aasm(state_machine_name).attribute_name => scope_name.to_s }
}
class_eval do
named_scope scope_name, :conditions => conditions
end
end
end
end
module InstanceMethods
private
def aasm_execute_after_commit
begin
require 'after_commit_everywhere'
raise LoadError unless Gem::Version.new(::AfterCommitEverywhere::VERSION) >= Gem::Version.new('0.1.5')
self.extend ::AfterCommitEverywhere
after_commit do
yield
end
rescue LoadError
warn <<-MSG
[DEPRECATION] :after_commit AASM callback is not safe in terms of race conditions and redundant calls.
Please add `gem 'after_commit_everywhere', '~> 1.0'` to your Gemfile in order to fix that.
MSG
yield
end
end
def aasm_raise_invalid_record
raise ActiveRecord::RecordInvalid.new(self)
end
def aasm_save
self.save
end
def aasm_update_column(attribute_name, value)
self.class.unscoped.where(self.class.primary_key => self.id).update_all(attribute_name => value) == 1
end
def aasm_read_attribute(name)
read_attribute(name)
end
def aasm_write_attribute(name, value)
write_attribute(name, value)
end
def aasm_transaction(requires_new, requires_lock)
self.class.transaction(:requires_new => requires_new) do
lock!(requires_lock) if requires_lock
yield
end
end
def aasm_enum(name=:default)
case AASM::StateMachineStore.fetch(self.class, true).machine(name).config.enum
when false then nil
when true then aasm_guess_enum_method(name)
when nil then aasm_guess_enum_method(name) if aasm_column_looks_like_enum(name)
else AASM::StateMachineStore.fetch(self.class, true).machine(name).config.enum
end
end
def aasm_column_looks_like_enum(name=:default)
column_name = self.class.aasm(name).attribute_name.to_s
column = self.class.columns_hash[column_name]
raise NoMethodError.new("undefined method '#{column_name}' for #{self.class}") if column.nil?
column.type == :integer
end
def aasm_guess_enum_method(name=:default)
self.class.aasm(name).attribute_name.to_s.pluralize.to_sym
end
def aasm_raw_attribute_value(state, name=:default)
if aasm_enum(name)
self.class.send(aasm_enum(name))[state]
else
super
end
end
# Ensures that if the aasm_state column is nil and the record is new
# then the initial state gets populated after initialization
#
# foo = Foo.new
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
# checking via respond_to? does not work in Rails <= 3
# if respond_to?(self.class.aasm(state_machine_name).attribute_name) && send(self.class.aasm(state_machine_name).attribute_name).blank? # Rails 4
if aasm_column_is_blank?(state_machine_name)
aasm(state_machine_name).enter_initial_state
end
end
end
def aasm_column_is_blank?(state_machine_name)
attribute_name = self.class.aasm(state_machine_name).attribute_name
attribute_names.include?(attribute_name.to_s) &&
(send(attribute_name).respond_to?(:empty?) ? !!send(attribute_name).empty? : !send(attribute_name))
end
def aasm_validate_states
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
unless aasm_skipping_validations(state_machine_name)
if aasm_invalid_state?(state_machine_name)
self.errors.add(AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.column , "is invalid")
end
end
end
end
def aasm_invalid_state?(state_machine_name)
aasm(state_machine_name).current_state && !aasm(state_machine_name).states.include?(aasm(state_machine_name).current_state)
end
end # InstanceMethods
end
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/base.rb | lib/aasm/persistence/base.rb | module AASM
module Persistence
module Base
def self.included(base) #:nodoc:
base.extend ClassMethods
end
# Returns the value of the aasm.attribute_name - called from <tt>aasm.current_state</tt>
#
# If it's a new record, and the aasm state column is blank it returns the initial state
# (example provided here for ActiveRecord, but it's true for Mongoid as well):
#
# class Foo < ActiveRecord::Base
# include AASM
# aasm :column => :status do
# state :opened
# state :closed
# end
# end
#
# foo = Foo.new
# foo.current_state # => :opened
# foo.close
# foo.current_state # => :closed
#
# foo = Foo.find(1)
# foo.current_state # => :opened
# foo.aasm_state = nil
# foo.current_state # => nil
#
# NOTE: intended to be called from an event
#
# This allows for nil aasm states - be sure to add validation to your model
def aasm_read_state(name=:default)
state = send(self.class.aasm(name).attribute_name)
if !state || state.empty?
aasm_new_record? ? aasm(name).determine_state_name(self.class.aasm(name).initial_state) : nil
else
state.to_sym
end
end
def aasm_new_record?
new_record?
end
module ClassMethods
def aasm_column(attribute_name=nil)
warn "[DEPRECATION] aasm_column is deprecated. Use aasm.attribute_name instead"
aasm.attribute_name(attribute_name)
end
end # ClassMethods
end # Base
end # Persistence
class Base
# make sure to create a (named) scope for each state
def state_with_scope(*args)
names = state_without_scope(*args)
names.each do |name|
create_scopes(name)
end
end
alias_method :state_without_scope, :state
alias_method :state, :state_with_scope
private
def create_scope?(name)
@state_machine.config.create_scopes && !@klass.respond_to?(name) && @klass.respond_to?(:aasm_create_scope)
end
def create_scope(name)
@klass.aasm_create_scope(@name, name) if create_scope?(name)
end
def create_scopes(name)
if namespace?
# Create default scopes even when namespace? for backward compatibility
namepaced_name = "#{namespace}_#{name}"
create_scope(namepaced_name)
end
create_scope(name)
end
end # Base
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/dynamoid_persistence.rb | lib/aasm/persistence/dynamoid_persistence.rb | module AASM
module Persistence
module DynamoidPersistence
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::DynamoidPersistence::InstanceMethods)
base.after_initialize :aasm_ensure_initial_state
# Because Dynamoid only use define_method to add attribute assignment method in Class.
#
# In AASM::Base.initialize, it redefines and calls super in this method without superclass method.
# We override method_missing to solve this problem.
#
base.class_eval %Q(
def method_missing(method_name, *arguments, &block)
if (AASM::StateMachineStore.fetch(self.class, true).machine_names.map { |state_machine_name| self.class.aasm(state_machine_name).attribute_name.to_s + "=" }).include? method_name.to_s
attribute_name = method_name.to_s.gsub("=", '')
write_attribute(attribute_name.to_sym, *arguments)
else
super
end
end
)
end
module InstanceMethods
# Writes <tt>state</tt> to the state column and persists it to the database
# using update_attribute (which bypasses validation)
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state, name=:default)
old_value = read_attribute(self.class.aasm(name).attribute_name)
write_attribute(self.class.aasm(name).attribute_name, state.to_s)
unless self.save(:validate => false)
write_attribute(self.class.aasm(name).attribute_name, old_value)
return false
end
true
end
# Writes <tt>state</tt> to the state column, but does not persist it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state, name=:default)
write_attribute(self.class.aasm(name).attribute_name, state.to_s)
end
private
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
aasm(state_machine_name).enter_initial_state if !send(self.class.aasm(state_machine_name).attribute_name) || send(self.class.aasm(state_machine_name).attribute_name).empty?
end
end
end # InstanceMethods
end
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/redis_persistence.rb | lib/aasm/persistence/redis_persistence.rb | module AASM
module Persistence
module RedisPersistence
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::RedisPersistence::InstanceMethods)
end
module InstanceMethods
# Initialize with default values
#
# Redis::Objects removes the key from Redis when set to `nil`
def initialize(*args)
super
aasm_ensure_initial_state
end
# Returns the value of the aasm.attribute_name - called from <tt>aasm.current_state</tt>
#
# If it's a new record, and the aasm state column is blank it returns the initial state
#
# class Foo
# include Redis::Objects
# include AASM
# aasm :column => :status do
# state :opened
# state :closed
# end
# end
#
# foo = Foo.new
# foo.current_state # => :opened
# foo.close
# foo.current_state # => :closed
#
# foo = Foo[1]
# foo.current_state # => :opened
# foo.aasm_state = nil
# foo.current_state # => nil
#
# NOTE: intended to be called from an event
#
# This allows for nil aasm states - be sure to add validation to your model
def aasm_read_state(name=:default)
state = send(self.class.aasm(name).attribute_name)
if state.value.nil?
nil
else
state.value.to_sym
end
end
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |name|
aasm_column = self.class.aasm(name).attribute_name
aasm(name).enter_initial_state if !send(aasm_column).value || send(aasm_column).value.empty?
end
end
# Writes <tt>state</tt> to the state column and persists it to the database
#
# foo = Foo[1]
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo[1].aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state, name=:default)
aasm_column = self.class.aasm(name).attribute_name
send("#{aasm_column}").value = state
end
# Writes <tt>state</tt> to the state column, but does not persist it to the database
# (but actually it still does)
#
# With Redis::Objects it's not possible to skip persisting - it's not an ORM,
# it does not operate like an AR model and does not know how to postpone changes.
#
# foo = Foo[1]
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo[1].aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo[1].aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state, name=:default)
aasm_write_state(state, name)
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/core_data_query_persistence.rb | lib/aasm/persistence/core_data_query_persistence.rb | module AASM
module Persistence
module CoreDataQueryPersistence
# This method:
#
# * extends the model with ClassMethods
# * includes InstanceMethods
#
# Adds
#
# after_initialize :aasm_ensure_initial_state
#
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::CoreDataQueryPersistence::InstanceMethods)
base.extend AASM::Persistence::CoreDataQueryPersistence::ClassMethods
base.after_initialize :aasm_ensure_initial_state
end
module ClassMethods
def aasm_create_scope(state_machine_name, scope_name)
scope(scope_name.to_sym, lambda { where(aasm(state_machine_name).attribute_name.to_sym).eq(scope_name.to_s) })
end
end
module InstanceMethods
# Writes <tt>state</tt> to the state column and persists it to the database
# using update_attribute (which bypasses validation)
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state, name=:default)
raise "Cowardly refusing to save the current CoreDataQuery context"
aasm_write_state_without_persistence(state, name)
end
# Writes <tt>state</tt> to the state column, but does not persist it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state, name=:default)
write_attribute(self.class.aasm(name).attribute_name, state.to_s)
end
private
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
next if !send(self.class.aasm(state_machine_name).attribute_name) || send(self.class.aasm(state_machine_name).attribute_name).empty?
send("#{self.class.aasm(state_machine_name).attribute_name}=", aasm(state_machine_name).enter_initial_state.to_s)
end
end
end # InstanceMethods
# module NamedScopeMethods
# def aasm_state_with_named_scope name, options = {}
# aasm_state_without_named_scope name, options
# self.named_scope name, :conditions => { "#{table_name}.#{self.aasm.attribute_name}" => name.to_s} unless self.respond_to?(name)
# end
# end
end
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/mongoid_persistence.rb | lib/aasm/persistence/mongoid_persistence.rb | require 'aasm/persistence/orm'
module AASM
module Persistence
module MongoidPersistence
# This method:
#
# * extends the model with ClassMethods
# * includes InstanceMethods
#
# Adds
#
# before_validation :aasm_ensure_initial_state
#
# As a result, it doesn't matter when you define your methods - the following 2 are equivalent
#
# class Foo
# include Mongoid::Document
# def aasm_write_state(state)
# "bar"
# end
# include AASM
# end
#
# class Foo
# include Mongoid::Document
# include AASM
# def aasm_write_state(state)
# "bar"
# end
# end
#
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::ORM)
base.send(:include, AASM::Persistence::MongoidPersistence::InstanceMethods)
base.extend AASM::Persistence::MongoidPersistence::ClassMethods
base.after_initialize :aasm_ensure_initial_state
end
module ClassMethods
def aasm_create_scope(state_machine_name, scope_name)
scope_options = lambda {
send(
:where,
{ aasm(state_machine_name).attribute_name.to_sym => scope_name.to_s }
)
}
send(:scope, scope_name, scope_options)
end
end
module InstanceMethods
private
def aasm_save
self.save
end
def aasm_raise_invalid_record
raise Mongoid::Errors::Validations.new(self)
end
def aasm_supports_transactions?
false
end
def aasm_update_column(attribute_name, value)
if Mongoid::VERSION.to_f >= 4
set(Hash[attribute_name, value])
else
set(attribute_name, value)
end
true
end
def aasm_read_attribute(name)
read_attribute(name)
end
def aasm_write_attribute(name, value)
write_attribute(name, value)
end
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
attribute_name = self.class.aasm(state_machine_name).attribute_name.to_s
# Do not load initial state when object attributes are not loaded,
# mongoid has_many relationship does not load child object attributes when
# only ids are loaded, for example parent.child_ids will not load child object attributes.
# This feature is introduced in mongoid > 4.
if attribute_names.include?(attribute_name) && !attributes[attribute_name] || attributes[attribute_name].empty?
# attribute_missing? is defined in mongoid > 4
return if Mongoid::VERSION.to_f >= 4 && attribute_missing?(attribute_name)
send("#{self.class.aasm(state_machine_name).attribute_name}=", aasm(state_machine_name).enter_initial_state.to_s)
end
end
end
end # InstanceMethods
# module NamedScopeMethods
# def aasm_state_with_named_scope name, options = {}
# aasm_state_without_named_scope name, options
# self.named_scope name, :conditions => { "#{table_name}.#{self.aasm.attribute_name}" => name.to_s} unless self.respond_to?(name)
# end
# end
end
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/sequel_persistence.rb | lib/aasm/persistence/sequel_persistence.rb | require 'aasm/persistence/orm'
module AASM
module Persistence
module SequelPersistence
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::ORM)
base.send(:include, AASM::Persistence::SequelPersistence::InstanceMethods)
end
module InstanceMethods
def before_validation
aasm_ensure_initial_state
super
end
def before_create
super
end
def aasm_raise_invalid_record
raise Sequel::ValidationFailed.new(self)
end
def aasm_new_record?
new?
end
# Returns nil if fails silently
# http://sequel.jeremyevans.net/rdoc/classes/Sequel/Model/InstanceMethods.html#method-i-save
def aasm_save
!save(raise_on_failure: false).nil?
end
def aasm_read_attribute(name)
send(name)
end
def aasm_write_attribute(name, value)
send("#{name}=", value)
end
def aasm_transaction(requires_new, requires_lock)
self.class.db.transaction(savepoint: requires_new) do
if requires_lock
# http://sequel.jeremyevans.net/rdoc/classes/Sequel/Model/InstanceMethods.html#method-i-lock-21
requires_lock.is_a?(String) ? lock!(requires_lock) : lock!
end
yield
end
end
def aasm_update_column(attribute_name, value)
this.update(attribute_name => value)
end
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |state_machine_name|
aasm(state_machine_name).enter_initial_state if
(new? || values.key?(self.class.aasm(state_machine_name).attribute_name)) &&
send(self.class.aasm(state_machine_name).attribute_name).to_s.strip.empty?
end
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence/no_brainer_persistence.rb | lib/aasm/persistence/no_brainer_persistence.rb | require 'aasm/persistence/orm'
module AASM
module Persistence
module NoBrainerPersistence
# This method:
#
# * extends the model with ClassMethods
# * includes InstanceMethods
#
# Adds
#
# before_validation :aasm_ensure_initial_state
#
# As a result, it doesn't matter when you define your methods - the following 2 are equivalent
#
# class Foo
# include NoBrainer::Document
# def aasm_write_state(state)
# "bar"
# end
# include AASM
# end
#
# class Foo
# include NoBrainer::Document
# include AASM
# def aasm_write_state(state)
# "bar"
# end
# end
#
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.send(:include, AASM::Persistence::ORM)
base.send(:include, AASM::Persistence::NoBrainerPersistence::InstanceMethods)
base.extend AASM::Persistence::NoBrainerPersistence::ClassMethods
base.after_initialize :aasm_ensure_initial_state
end
module ClassMethods
def aasm_create_scope(state_machine_name, scope_name)
scope_options = lambda {
where(aasm(state_machine_name).attribute_name.to_sym => scope_name.to_s)
}
send(:scope, scope_name, scope_options)
end
end
module InstanceMethods
private
def aasm_save
self.save
end
def aasm_raise_invalid_record
raise NoBrainer::Error::DocumentInvalid.new(self)
end
def aasm_supports_transactions?
false
end
def aasm_update_column(attribute_name, value)
write_attribute(attribute_name, value)
save(validate: false)
true
end
def aasm_read_attribute(name)
read_attribute(name)
end
def aasm_write_attribute(name, value)
write_attribute(name, value)
end
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
AASM::StateMachineStore.fetch(self.class, true).machine_names.each do |name|
aasm_column = self.class.aasm(name).attribute_name
aasm(name).enter_initial_state if !read_attribute(aasm_column) || read_attribute(aasm_column).empty?
end
end
end # InstanceMethods
end
end # Persistence
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/event.rb | lib/aasm/core/event.rb | # frozen_string_literal: true
module AASM::Core
class Event
include AASM::DslHelper
attr_reader :name, :state_machine, :options, :default_display_name
def initialize(name, state_machine, options = {}, &block)
@name = name
@state_machine = state_machine
@transitions = []
@valid_transitions = Hash.new { |h, k| h[k] = {} }
@guards = Array(options[:guard] || options[:guards] || options[:if])
@unless = Array(options[:unless]) #TODO: This could use a better name
@default_display_name = name.to_s.gsub(/_/, ' ').capitalize
# from aasm4
@options = options # QUESTION: .dup ?
add_options_from_dsl(@options, [
:after,
:after_commit,
:after_transaction,
:before,
:before_transaction,
:ensure,
:error,
:before_success,
:success,
], &block) if block
end
# called internally by Ruby 1.9 after clone()
def initialize_copy(orig)
super
@transitions = @transitions.collect { |transition| transition.clone }
@guards = @guards.dup
@unless = @unless.dup
@options = {}
orig.options.each_pair { |name, setting| @options[name] = setting.is_a?(Hash) || setting.is_a?(Array) ? setting.dup : setting }
end
# a neutered version of fire - it doesn't actually fire the event, it just
# executes the transition guards to determine if a transition is even
# an option given current conditions.
def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end
def fire(obj, options={}, to_state=::AASM::NO_VALUE, *args)
_fire(obj, options, to_state, *args) # false indicates this is not a test (fire!)
end
def transitions_from_state?(state)
transitions_from_state(state).any?
end
def transitions_from_state(state)
@transitions.select { |t| t.from.nil? or t.from == state }
end
def transitions_to_state?(state)
transitions_to_state(state).any?
end
def transitions_to_state(state)
@transitions.select { |t| t.to == state }
end
def fire_global_callbacks(callback_name, record, *args)
invoke_callbacks(state_machine.global_callbacks[callback_name], record, args)
end
def fire_callbacks(callback_name, record, *args)
# strip out the first element in args if it's a valid to_state
# #given where we're coming from, this condition implies args not empty
invoke_callbacks(@options[callback_name], record, args)
end
def fire_transition_callbacks(obj, *args)
from_state = obj.aasm(state_machine.name).current_state
transition = @valid_transitions[obj.object_id][from_state]
transition.invoke_success_callbacks(obj, *args) if transition
@valid_transitions.delete(obj.object_id)
end
def ==(event)
if event.is_a? Symbol
name == event
else
name == event.name
end
end
## DSL interface
def transitions(definitions=nil, &block)
if definitions # define new transitions
# Create a separate transition for each from-state to the given state
Array(definitions[:from]).each do |s|
@transitions << AASM::Core::Transition.new(self, attach_event_guards(definitions.merge(:from => s.to_sym)), &block)
end
# Create a transition if :to is specified without :from (transitions from ANY state)
if !definitions[:from] && definitions[:to]
@transitions << AASM::Core::Transition.new(self, attach_event_guards(definitions), &block)
end
end
@transitions
end
def failed_callbacks
transitions.flat_map(&:failures)
end
def to_s
name.to_s
end
private
def attach_event_guards(definitions)
unless @guards.empty?
given_guards = Array(definitions.delete(:guard) || definitions.delete(:guards) || definitions.delete(:if))
definitions[:guards] = @guards + given_guards # from aasm4
end
unless @unless.empty?
given_unless = Array(definitions.delete(:unless))
definitions[:unless] = given_unless + @unless
end
definitions
end
def _fire(obj, options={}, to_state=::AASM::NO_VALUE, *args)
result = options[:test_only] ? false : nil
clear_failed_callbacks
transitions = @transitions.select { |t| t.from == obj.aasm(state_machine.name).current_state || t.from == nil}
return result if transitions.size == 0
if to_state == ::AASM::NO_VALUE
to_state = nil
elsif !(to_state.respond_to?(:to_sym) && transitions.map(&:to).flatten.include?(to_state.to_sym))
# to_state is an argument
args.unshift(to_state)
to_state = nil
end
# nop, to_state is a valid to-state
transitions.each do |transition|
next if to_state and !Array(transition.to).include?(to_state)
if (options.key?(:may_fire) && transition.eql?(options[:may_fire])) ||
(!options.key?(:may_fire) && transition.allowed?(obj, *args))
if options[:test_only]
result = transition
else
result = to_state || Array(transition.to).first
Array(transition.to).each {|to| @valid_transitions[obj.object_id][to] = transition }
transition.execute(obj, *args)
end
break
end
end
result
end
def clear_failed_callbacks
# https://github.com/aasm/aasm/issues/383, https://github.com/aasm/aasm/issues/599
transitions.each { |transition| transition.failures.clear }
end
def invoke_callbacks(code, record, args)
Invoker.new(code, record, args)
.with_default_return_value(false)
.invoke
end
end
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/transition.rb | lib/aasm/core/transition.rb | # frozen_string_literal: true
module AASM::Core
class Transition
include AASM::DslHelper
attr_reader :from, :to, :event, :opts, :failures
alias_method :options, :opts
def initialize(event, opts, &block)
add_options_from_dsl(opts, [:on_transition, :guard, :after, :success], &block) if block
@event = event
@from = opts[:from]
@to = opts[:to]
@guards = Array(opts[:guards]) + Array(opts[:guard]) + Array(opts[:if])
@unless = Array(opts[:unless]) #TODO: This could use a better name
@failures = []
if opts[:on_transition]
warn '[DEPRECATION] :on_transition is deprecated, use :after instead'
opts[:after] = Array(opts[:after]) + Array(opts[:on_transition])
end
@after = Array(opts[:after])
@after = @after[0] if @after.size == 1
@success = Array(opts[:success])
@success = @success[0] if @success.size == 1
@opts = opts
end
# called internally by Ruby 1.9 after clone()
def initialize_copy(orig)
super
@guards = @guards.dup
@unless = @unless.dup
@opts = {}
orig.opts.each_pair { |name, setting| @opts[name] = setting.is_a?(Hash) || setting.is_a?(Array) ? setting.dup : setting }
end
def allowed?(obj, *args)
invoke_callbacks_compatible_with_guard(@guards, obj, args, :guard => true) &&
invoke_callbacks_compatible_with_guard(@unless, obj, args, :unless => true)
end
def execute(obj, *args)
invoke_callbacks_compatible_with_guard(event.state_machine.global_callbacks[:after_all_transitions], obj, args)
invoke_callbacks_compatible_with_guard(@after, obj, args)
end
def ==(obj)
@from == obj.from && @to == obj.to
end
def from?(value)
@from == value
end
def invoke_success_callbacks(obj, *args)
_fire_callbacks(@success, obj, args)
end
private
def invoke_callbacks_compatible_with_guard(code, record, args, options={})
if record.respond_to?(:aasm)
record.aasm(event.state_machine.name).from_state = @from if record.aasm(event.state_machine.name).respond_to?(:from_state=)
record.aasm(event.state_machine.name).to_state = @to if record.aasm(event.state_machine.name).respond_to?(:to_state=)
end
Invoker.new(code, record, args)
.with_options(options)
.with_failures(failures)
.invoke
end
def _fire_callbacks(code, record, args)
Invoker.new(code, record, args).invoke
end
end
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/state.rb | lib/aasm/core/state.rb | # frozen_string_literal: true
module AASM::Core
class State
attr_reader :name, :state_machine, :options, :default_display_name
def initialize(name, klass, state_machine, options={})
@name = name
@klass = klass
@state_machine = state_machine
@default_display_name = name.to_s.gsub(/_/, ' ').capitalize
update(options)
end
# called internally by Ruby 1.9 after clone()
def initialize_copy(orig)
super
@options = {}
orig.options.each_pair do |name, setting|
@options[name] = if setting.is_a?(Hash) || setting.is_a?(Array)
setting.dup
else
setting
end
end
end
def ==(state)
if state.is_a? Symbol
name == state
else
name == state.name
end
end
def <=>(state)
if state.is_a? Symbol
name <=> state
else
name <=> state.name
end
end
def to_s
name.to_s
end
def fire_callbacks(action, record, *args)
action = @options[action]
catch :halt_aasm_chain do
action.is_a?(Array) ?
action.each {|a| _fire_callbacks(a, record, args)} :
_fire_callbacks(action, record, args)
end
end
def display_name
@display_name = begin
if Module.const_defined?(:I18n)
localized_name
else
@default_display_name
end
end
end
def localized_name
AASM::Localizer.new.human_state_name(@klass, self)
end
alias human_name localized_name
def for_select
[display_name, name.to_s]
end
private
def update(options = {})
if options.key?(:display)
@default_display_name = options.delete(:display)
end
@options = options
self
end
def _fire_callbacks(action, record, args)
Invoker.new(action, record, args).invoke
end
end
end # AASM
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/invoker.rb | lib/aasm/core/invoker.rb | # frozen_string_literal: true
module AASM
module Core
##
# main invoker class which encapsulates the logic
# for invoking literal-based, proc-based, class-based
# and array-based callbacks for different entities.
class Invoker
DEFAULT_RETURN_VALUE = true
##
# Initialize a new invoker instance.
# NOTE that invoker must be used per-subject/record
# (one instance per subject/record)
#
# ==Options:
#
# +subject+ - invoking subject, may be Proc,
# Class, String, Symbol or Array
# +record+ - invoking record
# +args+ - arguments which will be passed to the callback
def initialize(subject, record, args)
@subject = subject
@record = record
@args = args
@options = {}
@failures = []
@default_return_value = DEFAULT_RETURN_VALUE
end
##
# Pass additional options to concrete invoker
#
# ==Options:
#
# +options+ - hash of options which will be passed to
# concrete invokers
#
# ==Example:
#
# with_options(guard: proc {...})
def with_options(options)
@options = options
self
end
##
# Collect failures to a specified buffer
#
# ==Options:
#
# +failures+ - failures buffer to collect failures
def with_failures(failures)
@failures = failures
self
end
##
# Change default return value of #invoke method
# if none of invokers processed the request.
#
# The default return value is #DEFAULT_RETURN_VALUE
#
# ==Options:
#
# +value+ - default return value for #invoke method
def with_default_return_value(value)
@default_return_value = value
self
end
##
# Find concrete invoker for specified subject and invoker it,
# or return default value set by #DEFAULT_RETURN_VALUE or
# overridden by #with_default_return_value
# rubocop:disable Metrics/AbcSize
def invoke
return invoke_array if subject.is_a?(Array)
return literal_invoker.invoke if literal_invoker.may_invoke?
return proc_invoker.invoke if proc_invoker.may_invoke?
return class_invoker.invoke if class_invoker.may_invoke?
default_return_value
end
# rubocop:enable Metrics/AbcSize
private
attr_reader :subject, :record, :args, :options, :failures,
:default_return_value
def invoke_array
return subject.all? { |item| sub_invoke(item) } if options[:guard]
return subject.all? { |item| !sub_invoke(item) } if options[:unless]
subject.map { |item| sub_invoke(item) }
end
def sub_invoke(new_subject)
self.class.new(new_subject, record, args)
.with_failures(failures)
.with_options(options)
.invoke
end
def proc_invoker
@proc_invoker ||= Invokers::ProcInvoker
.new(subject, record, args)
.with_failures(failures)
end
def class_invoker
@class_invoker ||= Invokers::ClassInvoker
.new(subject, record, args)
.with_failures(failures)
end
def literal_invoker
@literal_invoker ||= Invokers::LiteralInvoker
.new(subject, record, args)
.with_failures(failures)
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/invokers/literal_invoker.rb | lib/aasm/core/invokers/literal_invoker.rb | # frozen_string_literal: true
module AASM
module Core
module Invokers
##
# Literal invoker which allows to use strings or symbols to call
# record methods as state/event/transition callbacks.
class LiteralInvoker < BaseInvoker
def may_invoke?
subject.is_a?(String) || subject.is_a?(Symbol)
end
def log_failure
failures << subject
end
def invoke_subject
@result = exec_subject
end
private
def subject_arity
@arity ||= record.__send__(:method, subject.to_sym).arity
end
def exec_subject
ensure_method_exists
return simple_invoke if subject_arity.zero?
invoke_with_arguments
end
def ensure_method_exists
raise(*record_error) unless record.respond_to?(subject, true)
end
def simple_invoke
record.__send__(subject)
end
def invoke_with_arguments
if keyword_arguments?
instance_with_keyword_args
elsif subject_arity < 0
invoke_with_variable_arity
else
invoke_with_fixed_arity
end
end
def keyword_arguments?
params = record.method(subject).parameters
params.any? { |type, _| [:key, :keyreq].include?(type) }
end
def instance_with_keyword_args
positional_args, keyword_args = parse_arguments
if keyword_args.nil?
record.send(subject, *positional_args)
else
record.send(subject, *positional_args, **keyword_args)
end
end
def invoke_with_variable_arity
record.__send__(subject, *args)
end
def invoke_with_fixed_arity
req_args = args[0..(subject_arity - 1)]
if req_args[0].is_a?(Hash)
record.__send__(subject, **req_args[0])
else
record.__send__(subject, *req_args)
end
end
def record_error
[
NoMethodError,
'NoMethodError: undefined method ' \
"`#{subject}' for #{record.inspect}:#{record.class}"
]
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/invokers/proc_invoker.rb | lib/aasm/core/invokers/proc_invoker.rb | # frozen_string_literal: true
module AASM
module Core
module Invokers
##
# Proc invoker which allows to use Procs as
# state/event/transition callbacks.
class ProcInvoker < BaseInvoker
def may_invoke?
subject.is_a?(Proc)
end
def log_failure
return log_source_location if Method.method_defined?(:source_location)
log_proc_info
end
def invoke_subject
@result = if support_parameters?
exec_proc(parameters_to_arity)
else
exec_proc(subject.arity)
end
end
private
def support_parameters?
subject.respond_to?(:parameters)
end
def keyword_arguments?
return false unless support_parameters?
subject.parameters.any? { |type, _| [:key, :keyreq].include?(type) }
end
def exec_proc_with_keyword_args(parameters_size)
positional_args, keyword_args = parse_arguments
if keyword_args.nil?
if parameters_size < 0
record.instance_exec(*positional_args, &subject)
else
record.instance_exec(*positional_args[0..(parameters_size - 1)], &subject)
end
else
if parameters_size < 0
record.instance_exec(*positional_args, **keyword_args, &subject)
else
record.instance_exec(*positional_args[0..(parameters_size - 1)], **keyword_args, &subject)
end
end
end
# rubocop:disable Metrics/AbcSize
def exec_proc(parameters_size)
return record.instance_exec(&subject) if parameters_size.zero? && !keyword_arguments?
if keyword_arguments?
exec_proc_with_keyword_args(parameters_size)
elsif parameters_size < 0
record.instance_exec(*args, &subject)
else
record.instance_exec(*args[0..(parameters_size - 1)], &subject)
end
end
# rubocop:enable Metrics/AbcSize
def log_source_location
failures << subject.source_location.join('#')
end
def log_proc_info
failures << subject
end
def parameters_to_arity
subject.parameters.inject(0) do |memo, parameter|
case parameter[0]
when :key, :keyreq
# Keyword arguments don't count towards positional arity
when :rest
memo = memo > 0 ? -memo : -1
else
memo += 1
end
memo
end
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/invokers/base_invoker.rb | lib/aasm/core/invokers/base_invoker.rb | # frozen_string_literal: true
module AASM
module Core
module Invokers
##
# Base concrete invoker class which contain basic
# invoking and logging definitions
class BaseInvoker
attr_reader :failures, :subject, :record, :args, :result
##
# Initialize a new concrete invoker instance.
# NOTE that concrete invoker must be used per-subject/record
# (one instance per subject/record)
#
# ==Options:
#
# +subject+ - invoking subject comparable with this invoker
# +record+ - invoking record
# +args+ - arguments which will be passed to the callback
def initialize(subject, record, args)
@subject = subject
@record = record
@args = args
@result = false
@failures = []
end
##
# Collect failures to a specified buffer
#
# ==Options:
#
# +failures+ - failures buffer to collect failures
def with_failures(failures_buffer)
@failures = failures_buffer
self
end
##
# Execute concrete invoker, log the error and return result
def invoke
return unless may_invoke?
log_failure unless invoke_subject
result
end
##
# Check if concrete invoker may be invoked for a specified subject
def may_invoke?
raise NoMethodError, '"#may_invoke?" is not implemented'
end
##
# Log failed invoking
def log_failure
raise NoMethodError, '"#log_failure" is not implemented'
end
##
# Execute concrete invoker
def invoke_subject
raise NoMethodError, '"#invoke_subject" is not implemented'
end
##
# Parse arguments to separate keyword arguments from positional arguments
def parse_arguments
if args.last.is_a?(Hash)
[args[0..-2], args.last]
else
[args, nil]
end
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/core/invokers/class_invoker.rb | lib/aasm/core/invokers/class_invoker.rb | # frozen_string_literal: true
module AASM
module Core
module Invokers
##
# Class invoker which allows to use classes which respond to #call
# to be used as state/event/transition callbacks.
class ClassInvoker < BaseInvoker
def may_invoke?
subject.is_a?(Class) && subject.instance_methods.include?(:call)
end
def log_failure
return log_source_location if Method.method_defined?(:source_location)
log_method_info
end
def invoke_subject
@result = instance.call
end
private
def log_source_location
failures << instance.method(:call).source_location.join('#')
end
def log_method_info
failures << instance.method(:call)
end
def instance
@instance ||= retrieve_instance
end
def retrieve_instance
return subject.new if subject_arity.zero?
return subject.new(record) if subject_arity == 1
if keyword_arguments?
instance_with_keyword_args
elsif subject_arity < 0
subject.new(record, *args)
else
instance_with_fixed_arity
end
end
def keyword_arguments?
params = subject.instance_method(:initialize).parameters
params.any? { |type, _| [:key, :keyreq].include?(type) }
end
def instance_with_keyword_args
positional_args, keyword_args = parse_arguments
if keyword_args.nil?
subject.new(record, *positional_args)
else
subject.new(record, *positional_args, **keyword_args)
end
end
def instance_with_fixed_arity
subject.new(record, *args[0..(subject_arity - 2)])
end
def subject_arity
@arity ||= subject.instance_method(:initialize).arity
end
end
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/generate_action_mailer_specs.rb | example_app_generator/generate_action_mailer_specs.rb | require 'active_support'
require 'active_support/core_ext/module'
using_source_path(File.expand_path(__dir__)) do
# Comment out the default mailer stuff
comment_lines 'config/environments/development.rb', /action_mailer/
comment_lines 'config/environments/test.rb', /action_mailer/
initializer 'action_mailer.rb', <<-CODE
require "action_view/base"
if ENV['DEFAULT_URL']
ExampleApp::Application.configure do
config.action_mailer.default_url_options = { :host => ENV['DEFAULT_URL'] }
end
end
CODE
rails_parent = Rails.application.class.module_parent.to_s
gsub_file 'config/initializers/action_mailer.rb', /ExampleApp/, rails_parent
copy_file 'spec/support/default_preview_path'
chmod 'spec/support/default_preview_path', 0755
gsub_file 'spec/support/default_preview_path', /ExampleApp/, rails_parent
if skip_active_record?
comment_lines 'spec/support/default_preview_path', /active_record/
comment_lines 'spec/support/default_preview_path', /active_storage/
comment_lines 'spec/support/default_preview_path', /action_mailbox/
end
copy_file 'spec/verify_mailer_preview_path_spec.rb'
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/generate_app.rb | example_app_generator/generate_app.rb | require 'nokogiri'
rspec_rails_repo_path = File.expand_path('..', __dir__)
rspec_dependencies_gemfile = File.join(rspec_rails_repo_path, 'Gemfile-rspec-dependencies')
rails_dependencies_gemfile = File.join(rspec_rails_repo_path, 'Gemfile-rails-dependencies')
bundle_install_path = File.join(rspec_rails_repo_path, '..', 'bundle')
maintenance_branch_file = File.join(rspec_rails_repo_path, 'maintenance-branch')
ci_retry_script = File.join(
rspec_rails_repo_path,
'example_app_generator',
'ci_retry_bundle_install.sh'
)
function_script_file = File.join(rspec_rails_repo_path, 'script/functions.sh')
in_root do
prepend_to_file "Rakefile", "require 'active_support/all'"
# Remove the existing rails version so we can properly use main or other
# edge branches
gsub_file 'Gemfile', /^.*\bgem ['"]rails.*$/, ''
gsub_file 'Gemfile', /^.*\bgem ['"]selenium-webdriver.*$/, ''
gsub_file "Gemfile", /.*web-console.*/, ''
gsub_file "Gemfile", /.*debug.*/, ''
gsub_file "Gemfile", /.*puma.*/, ''
gsub_file "Gemfile", /.*bootsnap.*/, ''
append_to_file 'Gemfile', "gem 'rails-controller-testing'\n"
gsub_file "Gemfile", /.*rails-controller-testing.*/, "gem 'rails-controller-testing', git: 'https://github.com/rails/rails-controller-testing'"
# sqlite3 is an optional, unspecified, dependency of which Rails 8.0 only supports `~> 2.0`
if Rails::VERSION::STRING > '8'
gsub_file "Gemfile", /.*gem..sqlite3.*/, "gem 'sqlite3', '~> 2.0'"
else
gsub_file "Gemfile", /.*gem..sqlite3.*/, "gem 'sqlite3', '~> 1.7'"
end
# remove webdrivers
gsub_file "Gemfile", /gem ['"]webdrivers['"]/, ""
if RUBY_ENGINE == "jruby"
gsub_file "Gemfile", /.*jdbc.*/, ''
end
# Use our version of RSpec and Rails
append_to_file 'Gemfile', <<-EOT.gsub(/^ +\|/, '')
|gem 'rake', '>= 10.0.0'
|
|gem 'rspec-rails',
| :path => '#{rspec_rails_repo_path}',
| :groups => [:development, :test]
|eval_gemfile '#{rspec_dependencies_gemfile}'
|eval_gemfile '#{rails_dependencies_gemfile}'
EOT
copy_file maintenance_branch_file, 'maintenance-branch'
copy_file ci_retry_script, 'ci_retry_bundle_install.sh'
gsub_file 'ci_retry_bundle_install.sh',
'FUNCTIONS_SCRIPT_FILE',
function_script_file
gsub_file 'ci_retry_bundle_install.sh',
'REPLACE_BUNDLE_PATH',
bundle_install_path
chmod 'ci_retry_bundle_install.sh', 0755
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/run_specs.rb | example_app_generator/run_specs.rb | run('bin/rspec spec -cfdoc') || abort
# Ensure we test the issue in-case this isn't the first spec file loaded
run(
'bin/rspec --backtrace -cfdoc spec/__verify_fixture_load_order_spec.rb'
) || abort
run('bin/rake --backtrace spec') || abort
run('bin/rake --backtrace spec:requests') || abort
run('bin/rake --backtrace spec:models') || abort
run('bin/rake --backtrace spec:views') || abort
run('bin/rake --backtrace spec:controllers') || abort
run('bin/rake --backtrace spec:helpers') || abort
run('bin/rake --backtrace spec:mailers') || abort
run("bin/rails stats") || abort
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/generate_stuff.rb | example_app_generator/generate_stuff.rb | require 'rspec/rails/feature_check'
DEFAULT_SOURCE_PATH = File.expand_path(__dir__)
module ExampleAppHooks
module AR
def source_paths
@__source_paths__ ||= [DEFAULT_SOURCE_PATH]
end
def setup_tasks
# no-op
end
def final_tasks
copy_file 'spec/verify_active_record_spec.rb'
copy_file 'app/views/_example.html.erb'
copy_file 'app/views/foo.html'
copy_file 'app/views/some_templates/bar.html'
copy_file 'spec/verify_custom_renderers_spec.rb'
copy_file 'spec/verify_fixture_warning_spec.rb'
copy_file 'spec/verify_view_path_stub_spec.rb'
run('bin/rake db:migrate')
end
def skip_active_record?
false
end
end
module NoAR
def source_paths
@__source_paths__ ||= [File.join(DEFAULT_SOURCE_PATH, 'no_active_record')]
end
def setup_tasks
copy_file 'config/initializers/zeitwerk.rb'
copy_file 'app/models/in_memory/model.rb'
copy_file 'lib/rails/generators/in_memory/model/model_generator.rb'
copy_file 'lib/rails/generators/in_memory/model/templates/model.rb.erb'
application <<-CONFIG
config.generators do |g|
g.orm :in_memory, :migration => false
end
CONFIG
end
def final_tasks
copy_file 'spec/verify_no_active_record_spec.rb'
copy_file 'spec/verify_no_fixture_setup_spec.rb'
copy_file 'spec/verify_fixture_file_upload_spec.rb'
end
def skip_active_record?
true
end
end
def self.environment_hooks
if ENV['__RSPEC_NO_AR']
NoAR
else
AR
end
end
end
def generate(*)
super
$?.success? || abort
end
def using_source_path(path)
source_paths.unshift path
yield
ensure
# Remove our path munging
source_paths.shift
end
# Generally polluting `main` is bad as it monkey patches all objects. In this
# context, `self` is an _instance_ of a `Rails::Generators::AppGenerator`. So
# this won't pollute anything.
extend ExampleAppHooks.environment_hooks
setup_tasks
generate('rspec:install')
generate('controller wombats index') # plural
generate('controller welcome index') # singular
# request specs are now the default
generate('rspec:controller wombats --no-request-specs --controller-specs --no-view-specs')
generate('integration_test widgets') # deprecated
generate('mailer Notifications signup')
generate('model thing name:string')
generate('helper things')
generate('scaffold widget name:string category:string instock:boolean foo_id:integer bar_id:integer --force')
generate('scaffold gadget') # scaffold with no attributes
generate('scaffold ticket original_price:float discounted_price:float')
generate('scaffold admin/account name:string') # scaffold with nested resource
generate('scaffold card --api')
generate('scaffold upload --no-request_specs --controller_specs')
generate('rspec:feature gadget')
generate('controller things custom_action')
using_source_path(File.expand_path(__dir__)) do
# rspec-core loads files alphabetically, so we want this to be the first one
copy_file 'spec/features/model_mocks_integration_spec.rb'
end
begin
require 'action_mailbox'
run('rails action_mailbox:install')
rescue LoadError
end
begin
require 'active_job'
generate('job upload_backups')
rescue LoadError
end
begin
require 'action_cable'
require 'action_cable/test_helper'
generate('channel chat')
rescue LoadError
end
file "app/views/things/custom_action.html.erb",
"This is a template for a custom action.",
force: true
file "app/views/errors/401.html.erb",
"This is a template for rendering an error page",
force: true
# Use the absolute path so we can load it without active record too
apply File.join(DEFAULT_SOURCE_PATH, 'generate_action_mailer_specs.rb')
using_source_path(File.expand_path(__dir__)) do
# rspec-core loads files alphabetically, so we want this to be the first one
copy_file 'spec/__verify_fixture_load_order_spec.rb'
end
gsub_file 'spec/spec_helper.rb', /^=(begin|end)/, ''
gsub_file 'spec/rails_helper.rb', /^# Rails\.root\.glob\('spec.support/, "Rails.root.glob('spec/support"
# Warnings are too noisy in the sample apps
gsub_file 'spec/spec_helper.rb',
'config.warnings = true',
'config.warnings = false'
gsub_file '.rspec', '--warnings', ''
# Make a generated file work
gsub_file 'app/views/cards/_card.json.jbuilder',
', :created_at, :updated_at',
''
# Remove skips so we can test specs work
gsub_file 'spec/requests/cards_spec.rb',
'skip("Add a hash of attributes valid for your model")',
'{}'
gsub_file 'spec/requests/gadgets_spec.rb',
'skip("Add a hash of attributes valid for your model")',
'{}'
gsub_file 'spec/controllers/uploads_controller_spec.rb',
'skip("Add a hash of attributes valid for your model")',
'{}'
final_tasks
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/app/models/in_memory/model.rb | example_app_generator/no_active_record/app/models/in_memory/model.rb | raise "ActiveRecord is defined but should not be!" if defined?(::ActiveRecord)
require 'active_model'
module InMemory
module Persistence
def all
@all_records ||= []
end
def count
all.length
end
alias_method :size, :count
alias_method :length, :count
def last
all.last
end
def find(id)
id = id.to_i
all.find { |record| record.id == id } || raise
end
def create!(attributes = {})
record = new(attributes)
record.save
record
end
def next_id
@id_count ||= 0
@id_count += 1
end
end
class Model
extend Persistence
if defined?(::ActiveModel::Model)
include ::ActiveModel::Model
else
extend ::ActiveModel::Naming
include ::ActiveModel::Conversion
include ::ActiveModel::Validations
def initialize(attributes = {})
assign_attributes(attributes)
end
end
attr_accessor :id, :persisted
alias_method :persisted?, :persisted
def update(attributes)
assign_attributes(attributes)
save
end
alias_method :update_attributes, :update
def assign_attributes(attributes)
attributes.each do |name, value|
__send__("#{name}=", value)
end
end
def save(*)
self.id = self.class.next_id
self.class.all << self
true
end
alias :save! :save
def destroy
self.class.all.delete(self)
true
end
alias :destroy! :destroy
def reload(*)
self
end
def ==(other)
other.is_a?(self.class) && id == other.id
end
def persisted?
!id.nil?
end
def new_record?
!persisted?
end
def to_param
id.to_s
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/spec/verify_no_active_record_spec.rb | example_app_generator/no_active_record/spec/verify_no_active_record_spec.rb | require 'rails_helper'
RSpec.describe 'Example App' do
it "does not have ActiveRecord defined" do
expect(defined?(ActiveRecord)).not_to be
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/spec/verify_no_fixture_setup_spec.rb | example_app_generator/no_active_record/spec/verify_no_fixture_setup_spec.rb | # Pretend that ActiveRecord::Rails is defined and this doesn't blow up
# with `config.use_active_record = false`.
# Trick the other spec that checks that ActiveRecord is
# *not* defined by wrapping it in RSpec::Rails namespace
# so that it's reachable from RSpec::Rails::FixtureSupport.
# NOTE: this has to be defined before requiring `rails_helper`.
module RSpec
module Rails
module ActiveRecord
module TestFixtures
end
end
end
end
require 'rails_helper'
RSpec.describe 'Example App', :use_fixtures, type: :model do
it "does not set up fixtures" do
expect(defined?(fixtures)).not_to be
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/spec/verify_fixture_file_upload_spec.rb | example_app_generator/no_active_record/spec/verify_fixture_file_upload_spec.rb | require 'rails_helper'
RSpec.describe 'Example App', :use_fixtures, type: :model do
it 'supports fixture file upload' do
file = fixture_file_upload(__FILE__)
expect(file.read).to match(/RSpec\.describe 'Example App'/im)
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/lib/rails/generators/in_memory/model/model_generator.rb | example_app_generator/no_active_record/lib/rails/generators/in_memory/model/model_generator.rb | # Hook into the work already done to support older Rails
require 'generators/rspec'
module InMemory
module Generators
class ModelGenerator < ::Rspec::Generators::Base
source_root File.expand_path('templates', __dir__)
desc "Creates a Fake ActiveRecord acting model"
argument :attributes,
type: :array,
default: [],
banner: "field:type field:type"
check_class_collision
class_option :parent,
type: :string,
desc: "The parent class for the generated model"
def create_model_file
template "model.rb.erb",
File.join("app/models", class_path, "#{file_name}.rb")
end
hook_for :test_framework
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/no_active_record/config/initializers/zeitwerk.rb | example_app_generator/no_active_record/config/initializers/zeitwerk.rb | if Rails.autoloaders.respond_to?(:main) && Rails.autoloaders.main.respond_to?(:ignore)
Rails.autoloaders.main.ignore('lib/rails/generators/in_memory/model/model_generator.rb')
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/verify_fixture_warning_spec.rb | example_app_generator/spec/verify_fixture_warning_spec.rb | require 'rails_helper'
RSpec.describe "Fixture warnings" do
def generate_fixture_example_group(hook_type)
RSpec.describe do
include RSpec::Rails::RailsExampleGroup
fixtures :things
before(hook_type) do
things :a
end
it "" do
end
end
end
it "Warns when a fixture call is made in a before :context call" do
expect(RSpec).to receive(:warn_with).with(match(/Calling fixture method in before :context/))
generate_fixture_example_group(:context).run
end
it "Does not warn when a fixture call is made in a before :each call" do
expect(RSpec).not_to receive(:warn_with)
generate_fixture_example_group(:each).run
end
end
RSpec.describe "Global fixture warnings" do
def generate_fixture_example_group(hook_type)
RSpec.describe do
include RSpec::Rails::RailsExampleGroup
before(hook_type) do
things :a
end
it "" do
end
end
end
around do |ex|
RSpec.configuration.global_fixtures = [:things]
ex.call
RSpec.configuration.global_fixtures = []
end
it "warns when a global fixture call is made in a before :context call" do
expect(RSpec).to receive(:warn_with).with(match(/Calling fixture method in before :context/))
generate_fixture_example_group(:context).run
end
it "does not warn when a global fixture call is made in a before :each call" do
expect(RSpec).not_to receive(:warn_with)
generate_fixture_example_group(:each).run
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/verify_active_record_spec.rb | example_app_generator/spec/verify_active_record_spec.rb | require 'rails_helper'
RSpec.describe 'Example App' do
it "has ActiveRecord defined" do
expect(defined?(ActiveRecord)).to be
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/__verify_fixture_load_order_spec.rb | example_app_generator/spec/__verify_fixture_load_order_spec.rb | # This spec needs to be run before `rails_helper` is loaded to check the issue
RSpec.describe "Verify issue rspec/rspec-rails#1355" do
it "passes" do
expect(1).to eq 1
end
end
require 'rails_helper'
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/verify_custom_renderers_spec.rb | example_app_generator/spec/verify_custom_renderers_spec.rb | require 'rails_helper'
RSpec.describe "template rendering", type: :controller do
context "without render_views" do
context "with the standard renderers" do
controller do
def index
render template: 'foo', layout: false
end
end
it "renders the 'foo' template" do
get :index
expect(response).to render_template(:foo)
end
it "renders an empty string" do
get :index
expect(response.body).to eq("")
end
end
context "with a String path prepended to the view path" do
controller do
def index
prepend_view_path('app/views/some_templates')
render template: 'bar', layout: false
end
end
it "renders the 'bar' template" do
get :index
expect(response).to render_template(:bar)
end
end
context "with a custom renderer prepended to the view path" do
controller do
def index
prepend_view_path(MyResolver.new)
render template: 'baz', layout: false
end
end
it "renders the 'baz' template" do
get :index
expect(response).to render_template(:baz)
end
it "renders an empty string" do
get :index
expect(response.body).to eq("")
end
end
end
context "with render_views enabled" do
render_views
context "with the standard renderers" do
controller do
def index
render template: 'foo', layout: false
end
end
it "renders the 'foo' template" do
get :index
expect(response).to render_template(:foo)
end
it "renders the contents of the template" do
get :index
expect(response.body).to include("Static template named 'foo.html'")
end
end
context "with a String path prepended to the view path" do
controller do
def index
prepend_view_path('app/views/some_templates')
render template: 'bar', layout: false
end
end
it "renders the 'bar' template" do
get :index
expect(response).to render_template(:bar)
end
it "renders the contents of the template" do
get :index
expect(response.body).to include("Static template named 'bar.html'")
end
end
context "with a custom renderer prepended to the view path" do
controller do
def index
prepend_view_path(MyResolver.new)
render template: 'baz', layout: false
end
end
it "renders the 'baz' template" do
get :index
expect(response).to render_template(:baz)
end
it "renders the contents of the template" do
get :index
expect(response.body).to eq("Dynamic template with path '/baz'")
end
end
end
class MyResolver < ActionView::Resolver
private
def find_templates(name, prefix = nil, partial = false, _details = {}, _key = nil, _locals = [])
name.prepend("_") if partial
path = [prefix, name].join("/")
template = find_template(name, path)
[template]
end
def find_template(name, path)
ActionView::Template.new(
"",
name,
->(template, _source = nil) { %("Dynamic template with path '#{template.virtual_path}'") },
virtual_path: path,
format: :html,
locals: []
)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/verify_mailer_preview_path_spec.rb | example_app_generator/spec/verify_mailer_preview_path_spec.rb | require 'rails_helper'
require 'rspec/rails/feature_check'
RSpec.describe 'Action Mailer railtie hook' do
CaptureExec = Struct.new(:io, :exit_status) do
def ==(str)
io == str
end
end
def as_commandline(ops)
cmd, ops = ops.reverse
ops ||= {}
cmd_parts = ops.map { |k, v| "#{k}=#{v}" } << cmd << '2>&1'
cmd_parts.join(' ')
end
def capture_exec(*ops)
ops << { err: [:child, :out] }
lines = []
_process =
IO.popen(ops) do |io|
while (line = io.gets)
lines << line
end
end
# Necessary to ignore warnings from Rails code base
out = lines
.reject { |line| line =~ /warning: circular argument reference/ }
.reject { |line| line =~ /Gem::Specification#rubyforge_project=/ }
.reject { |line| line =~ /DEPRECATION WARNING/ }
.reject { |line| line =~ /warning: previous/ }
.reject { |line| line =~ /warning: already/ }
.reject { |line| line =~ /but will no longer be part of the default gems / }
.reject { |line| line =~ /You can add .* to your Gemfile/ }
.join
.chomp
CaptureExec.new(out, $?.exitstatus)
end
let(:expected_custom_path) { "/custom/path\n#{::Rails.root}/test/mailers/previews" }
let(:expected_rspec_path) { "#{::Rails.root}/spec/mailers/previews\n#{::Rails.root}/test/mailers/previews" }
def have_no_preview(opts = {})
expected_io =
if opts[:actually_blank]
be_blank
else
"#{::Rails.root}/test/mailers/previews"
end
have_attributes(io: expected_io, exit_status: 0)
end
let(:exec_script) {
File.expand_path(File.join(__FILE__, '../support/default_preview_path'))
}
if RSpec::Rails::FeatureCheck.has_action_mailer_preview?
context 'in the development environment' do
let(:custom_env) { { 'RAILS_ENV' => rails_env } }
let(:rails_env) { 'development' }
it 'sets the preview path to the default rspec path' do
skip "this spec fails singularly on JRuby due to weird env things" if RUBY_ENGINE == "jruby"
expect(capture_exec(custom_env, exec_script)).to eq(expected_rspec_path)
end
it 'respects the setting from `show_previews`' do
expect(
capture_exec(
custom_env.merge('SHOW_PREVIEWS' => 'false'),
exec_script
)
).to have_no_preview
end
it 'respects a custom `preview_path`' do
expect(
capture_exec(
custom_env.merge('CUSTOM_PREVIEW_PATH' => '/custom/path'),
exec_script
)
).to eq(expected_custom_path)
end
it 'allows initializers to set options' do
expect(
capture_exec(
custom_env.merge('DEFAULT_URL' => 'test-host'),
exec_script
)
).to eq('test-host')
end
it 'handles action mailer not being available' do
expect(
capture_exec(
custom_env.merge('NO_ACTION_MAILER' => 'true'),
exec_script
)
).to have_no_preview(actually_blank: true)
end
end
context 'in a non-development environment' do
let(:custom_env) { { 'RAILS_ENV' => rails_env } }
let(:rails_env) { 'test' }
it 'does not set the preview path by default' do
expect(capture_exec(custom_env, exec_script)).to have_no_preview
end
it 'respects the setting from `show_previews`' do
expect(
capture_exec(custom_env.merge('SHOW_PREVIEWS' => 'true'), exec_script)
).to eq(expected_rspec_path)
end
it 'allows initializers to set options' do
expect(
capture_exec(
custom_env.merge('DEFAULT_URL' => 'test-host'),
exec_script
)
).to eq('test-host')
end
end
else
context 'in the development environment' do
let(:custom_env) { { 'RAILS_ENV' => rails_env } }
let(:rails_env) { 'development' }
it 'handles no action mailer preview' do
expect(capture_exec(custom_env, exec_script)).to have_no_preview
end
it 'allows initializers to set options' do
expect(
capture_exec(
custom_env.merge('DEFAULT_URL' => 'test-host'),
exec_script
)
).to eq('test-host')
end
it 'handles action mailer not being available' do
expect(
capture_exec(
custom_env.merge('NO_ACTION_MAILER' => 'true'),
exec_script
)
).to have_no_preview
end
end
context 'in a non-development environment' do
let(:custom_env) { { 'RAILS_ENV' => rails_env } }
let(:rails_env) { 'test' }
it 'handles no action mailer preview' do
expect(capture_exec(custom_env, exec_script)).to have_no_preview
end
it 'allows initializers to set options' do
expect(
capture_exec(
custom_env.merge('DEFAULT_URL' => 'test-host'),
exec_script
)
).to eq('test-host')
end
it 'handles action mailer not being available' do
expect(
capture_exec(
custom_env.merge('NO_ACTION_MAILER' => 'true'),
exec_script
)
).to have_no_preview
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/verify_view_path_stub_spec.rb | example_app_generator/spec/verify_view_path_stub_spec.rb | require 'rails_helper'
RSpec.describe "verify view path doesn't leak stubs between examples", type: :view, order: :defined do
subject(:html) do
render partial: "example"
rendered
end
it "renders the stub template" do
stub_template("_example.html.erb" => "STUB_HTML")
expect(html).to include("STUB_HTML")
end
it "renders the file template" do
expect(html).to include("TEMPLATE_HTML")
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/example_app_generator/spec/features/model_mocks_integration_spec.rb | example_app_generator/spec/features/model_mocks_integration_spec.rb | require 'rails_helper'
RSpec.describe "Using rspec-mocks with models" do
it "supports stubbing class methods on models" do
allow(Widget).to receive(:all).and_return(:any_stub)
expect(Widget.all).to be :any_stub
end
it "supports stubbing attribute methods on models" do
a_widget = Widget.new
allow(a_widget).to receive(:name).and_return("Any Stub")
expect(a_widget.name).to eq "Any Stub"
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/benchmarks/before_block_capture_block_vs_yield.rb | benchmarks/before_block_capture_block_vs_yield.rb | require 'benchmark/ips'
def before_n_times(n, &block)
n.times { instance_exec(&block) }
end
def yield_n_times(n)
before_n_times(n) { yield }
end
def capture_block_and_yield_n_times(n, &block) # rubocop:disable Lint/UnusedMethodArgument
before_n_times(n) { yield }
end
def capture_block_and_call_n_times(n, &block)
before_n_times(n) { block.call }
end
[10, 25, 50, 100, 1000, 10_000].each do |count|
puts "\n\nInvoking the block #{count} times\n"
Benchmark.ips do |x|
x.report("Yield #{count} times ") do
yield_n_times(count) { }
end
x.report("Capture block and yield #{count} times") do
capture_block_and_yield_n_times(count) { }
end
x.report("Capture block and call #{count} times ") do
capture_block_and_call_n_times(count) { }
end
end
end
__END__
This attempts to measure the performance of how `routes` works in RSpec. It's
actually a method which delegates to `before`. RSpec executes `before` hooks by
capturing the block and then performing an `instance_exec` on it later in the
example context.
rspec-core has already performed [many related benchmarks about
this](https://github.com/rspec/rspec/tree/main/rspec-core/benchmarks):
- [call vs yield](https://github.com/rspec/rspec/blob/main/rspec-core/benchmarks/call_v_yield.rb)
- [capture block vs yield](https://github.com/rspec/rspec/blob/main/rspec-core/benchmarks/capture_block_vs_yield.rb)
- [flat map vs inject](https://github.com/rspec/rspec/blob/main/rspec-core/benchmarks/flat_map_vs_inject.rb)
The results are very interesting:
> This benchmark demonstrates that capturing a block (e.g. `&block`) has
> a high constant cost, taking about 5x longer than a single `yield`
> (even if the block is never used!).
>
> However, forwarding a captured block can be faster than using `yield`
> if the block is used many times (the breakeven point is at about 20-25
> invocations), so it appears that he per-invocation cost of `yield`
> is higher than that of a captured-and-forwarded block.
>
> Note that there is no circumstance where using `block.call` is faster.
>
> See also `flat_map_vs_inject.rb`, which appears to contradict these
> results a little bit.
>
> -- https://github.com/rspec/rspec/blob/main/rspec-core/benchmarks/capture_block_vs_yield.rb#L83-L95
and
> Surprisingly, `flat_map(&block)` appears to be faster than
> `flat_map { yield }` in spite of the fact that our array here
> is smaller than the break-even point of 20-25 measured in the
> `capture_block_vs_yield.rb` benchmark. In fact, the forwarded-block
> version remains faster in my benchmarks here no matter how small
> I shrink the `words` array. I'm not sure why!
>
> -- https://github.com/rspec/rspec/blob/main/rspec-core/benchmarks/flat_map_vs_inject.rb#L37-L42
This seems to show that the error margin is enough to negate any benefit from
capturing the block initially. It also shows that not capturing the block is
still faster at low rates of calling. If this holds for your system, I think
this PR is good as is and we won't need to capture the block in the `route`
method, but still use `yield`.
My results using Ruby 2.2.0:
Invoking the block 10 times
Calculating -------------------------------------
Yield 10 times
13.127k i/100ms
Capture block and yield 10 times
12.975k i/100ms
Capture block and call 10 times
11.524k i/100ms
-------------------------------------------------
Yield 10 times
165.030k (± 5.7%) i/s - 827.001k
Capture block and yield 10 times
163.866k (± 5.9%) i/s - 817.425k
Capture block and call 10 times
137.892k (± 7.3%) i/s - 691.440k
Invoking the block 25 times
Calculating -------------------------------------
Yield 25 times
7.305k i/100ms
Capture block and yield 25 times
7.314k i/100ms
Capture block and call 25 times
6.047k i/100ms
-------------------------------------------------
Yield 25 times
84.167k (± 5.6%) i/s - 423.690k
Capture block and yield 25 times
82.110k (± 6.4%) i/s - 409.584k
Capture block and call 25 times
67.144k (± 6.2%) i/s - 338.632k
Invoking the block 50 times
Calculating -------------------------------------
Yield 50 times
4.211k i/100ms
Capture block and yield 50 times
4.181k i/100ms
Capture block and call 50 times
3.410k i/100ms
-------------------------------------------------
Yield 50 times
45.223k (± 5.0%) i/s - 227.394k
Capture block and yield 50 times
45.253k (± 4.9%) i/s - 225.774k
Capture block and call 50 times
36.181k (± 5.7%) i/s - 180.730k
Invoking the block 100 times
Calculating -------------------------------------
Yield 100 times
2.356k i/100ms
Capture block and yield 100 times
2.305k i/100ms
Capture block and call 100 times
1.842k i/100ms
-------------------------------------------------
Yield 100 times
23.677k (± 7.1%) i/s - 117.800k
Capture block and yield 100 times
24.039k (± 4.7%) i/s - 122.165k
Capture block and call 100 times
18.888k (± 6.6%) i/s - 95.784k
Invoking the block 1000 times
Calculating -------------------------------------
Yield 1000 times
244.000 i/100ms
Capture block and yield 1000 times
245.000 i/100ms
Capture block and call 1000 times
192.000 i/100ms
-------------------------------------------------
Yield 1000 times
2.540k (± 4.3%) i/s - 12.688k
Capture block and yield 1000 times
2.499k (± 5.6%) i/s - 12.495k
Capture block and call 1000 times
1.975k (± 5.1%) i/s - 9.984k
Invoking the block 10000 times
Calculating -------------------------------------
Yield 10000 times
24.000 i/100ms
Capture block and yield 10000 times
24.000 i/100ms
Capture block and call 10000 times
19.000 i/100ms
-------------------------------------------------
Yield 10000 times
232.923 (±15.5%) i/s - 1.128k
Capture block and yield 10000 times
212.504 (±21.6%) i/s - 936.000
Capture block and call 10000 times
184.090 (±10.3%) i/s - 912.000
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/snippets/include_activesupport_testing_tagged_logger.rb | snippets/include_activesupport_testing_tagged_logger.rb | if __FILE__ =~ /^snippets/
fail "Snippets are supposed to be run from their own directory to avoid side " \
"effects as e.g. the root `Gemfile`, or `spec/spec_helpers.rb` to be " \
"loaded by the root `.rspec`."
end
# We opt-out from using RubyGems, but `bundler/inline` requires it
require 'rubygems'
require "bundler/inline"
# We pass `false` to `gemfile` to skip the installation of gems,
# because it may install versions that would conflict with versions
# from the main `Gemfile.lock`.
gemfile(false) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Those Gemfiles carefully pick the right versions depending on
# settings in the ENV, `.rails-version` and `maintenance-branch`.
Dir.chdir('..') do
# This Gemfile expects `maintenance-branch` file to be present
# in the current directory.
eval_gemfile 'Gemfile-rspec-dependencies'
# This Gemfile expects `.rails-version` file
eval_gemfile 'Gemfile-rails-dependencies'
end
gem "rspec-rails", path: "../"
end
# Run specs at exit
require "rspec/autorun"
require "rails"
require "active_record/railtie"
require "active_job/railtie"
require "rspec/rails"
ActiveJob::Base.queue_adapter = :test
# This connection will do for database-independent bug reports
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
class TestError < StandardError; end
class TestJob < ActiveJob::Base
def perform
raise TestError
end
end
RSpec.describe 'Foo', type: :job do
include ::ActiveJob::TestHelper
describe 'error raised in perform_enqueued_jobs with block' do
it 'raises the explicitly thrown error' do
expected_error = Minitest::UnexpectedError.new(TestError)
expect { perform_enqueued_jobs { TestJob.perform_later } }
.to raise_error(expected_error)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/snippets/avoid_fixture_name_collision.rb | snippets/avoid_fixture_name_collision.rb | if __FILE__ =~ /^snippets/
fail "Snippets are supposed to be run from their own directory to avoid side " \
"effects as e.g. the root `Gemfile`, or `spec/spec_helpers.rb` to be " \
"loaded by the root `.rspec`."
end
# We opt-out from using RubyGems, but `bundler/inline` requires it
require 'rubygems'
require "bundler/inline"
# We pass `false` to `gemfile` to skip the installation of gems,
# because it may install versions that would conflict with versions
# from the main `Gemfile.lock`.
gemfile(false) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Those Gemfiles carefully pick the right versions depending on
# settings in the ENV, `.rails-version` and `maintenance-branch`.
Dir.chdir('..') do
# This Gemfile expects `maintenance-branch` file to be present
# in the current directory.
eval_gemfile 'Gemfile-rspec-dependencies'
# This Gemfile expects `.rails-version` file
eval_gemfile 'Gemfile-rails-dependencies'
end
gem "rspec-rails", path: "../"
end
# Run specs at exit
require "rspec/autorun"
require "rails"
require "active_record/railtie"
require "rspec/rails"
# This connection will do for database-independent bug reports
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
RSpec.describe 'Foo' do
subject { true }
let(:name) { raise "Should never raise" }
it { is_expected.to be_truthy }
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/snippets/use_active_record_false.rb | snippets/use_active_record_false.rb | if __FILE__ =~ /^snippets/
fail "Snippets are supposed to be run from their own directory to avoid side " \
"effects as e.g. the root `Gemfile`, or `spec/spec_helpers.rb` to be " \
"loaded by the root `.rspec`."
end
# We opt-out from using RubyGems, but `bundler/inline` requires it
require 'rubygems'
require "bundler/inline"
# We pass `false` to `gemfile` to skip the installation of gems,
# because it may install versions that would conflict with versions
# from the main `Gemfile.lock`.
gemfile(false) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Those Gemfiles carefully pick the right versions depending on
# settings in the ENV, `.rails-version` and `maintenance-branch`.
Dir.chdir('..') do
# This Gemfile expects `maintenance-branch` file to be present
# in the current directory.
eval_gemfile 'Gemfile-rspec-dependencies'
# This Gemfile expects `.rails-version` file
eval_gemfile 'Gemfile-rails-dependencies'
end
gem "rspec-rails", path: "../"
end
# Run specs at exit
require "rspec/autorun"
# This snippet describes the case when ActiveRecord is loaded, but
# `use_active_record` is set to `false` in RSpec configuration.
# Initialization
require "active_record/railtie"
require "rspec/rails"
# This connection will do for database-independent bug reports
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
# RSpec configuration
RSpec.configure do |config|
config.use_active_record = false
end
# Rails project code
class Foo
end
# Rails project specs
RSpec.describe Foo do
it 'does not not break' do
Foo
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/yard/template/default/layout/html/setup.rb | yard/template/default/layout/html/setup.rb | # Docs suggest I don't need this, but ...
YARD::Server::Commands::StaticFileCommand::STATIC_PATHS << File.expand_path('../../fulldoc/html', __dir__)
def stylesheets
super + ['css/rspec.css']
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/features/support/capybara.rb | features/support/capybara.rb | Around "@capybara" do |_scenario, block|
require 'capybara'
block.call
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/features/support/env.rb | features/support/env.rb | require 'aruba/cucumber'
require 'fileutils'
module ArubaExt
def run_command_and_stop(cmd, opts = {})
exec_cmd = cmd =~ /^rspec/ ? "bin/#{cmd}" : cmd
unset_bundler_env_vars
# Ensure the correct Gemfile and binstubs are found
in_current_directory do
with_unbundled_env do
super(exec_cmd, opts)
end
end
end
def unset_bundler_env_vars
empty_env = with_environment { with_unbundled_env { ENV.to_h } }
aruba_env = aruba.environment.to_h
(aruba_env.keys - empty_env.keys).each do |key|
delete_environment_variable key
end
empty_env.each do |k, v|
set_environment_variable k, v
end
end
def with_unbundled_env
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env { yield }
else
Bundler.with_clean_env { yield }
end
end
end
World(ArubaExt)
Aruba.configure do |config|
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'truffleruby'
config.exit_timeout = 120
else
config.exit_timeout = 30
end
end
unless File.directory?('./tmp/example_app')
system "rake generate:app generate:stuff"
end
Before do
example_app_dir = 'tmp/example_app'
# Per default Aruba will create a directory tmp/aruba where it performs its file operations.
# https://github.com/cucumber/aruba/blob/v0.6.1/README.md#use-a-different-working-directory
aruba_dir = 'tmp/aruba'
# Remove the previous aruba workspace.
FileUtils.rm_rf(aruba_dir) if File.exist?(aruba_dir)
# We want fresh `example_app` project with empty `spec` dir except helpers.
# FileUtils.cp_r on Ruby 1.9.2 doesn't preserve permissions.
system('cp', '-r', example_app_dir, aruba_dir)
helpers = %w[spec/spec_helper.rb spec/rails_helper.rb]
directories = []
Dir["#{aruba_dir}/spec/**/*"].each do |path|
next if helpers.any? { |helper| path.end_with?(helper) }
# Because we now check for things like spec/support we only want to delete empty directories
if File.directory?(path)
directories << path
next
end
FileUtils.rm_rf(path)
end
directories.each { |dir| FileUtils.rm_rf(dir) if Dir.empty?(dir) }
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/features/step_definitions/additional_cli_steps.rb | features/step_definitions/additional_cli_steps.rb | begin
require "active_job"
rescue LoadError # rubocop:disable Lint/SuppressedException
end
begin
require "action_cable"
rescue LoadError # rubocop:disable Lint/SuppressedException
end
begin
require "active_storage"
require "action_mailbox"
rescue LoadError # rubocop:disable Lint/SuppressedException
end
require "rails/version"
require "rspec/rails/feature_check"
Then /^the example(s)? should( all)? pass$/ do |_, _|
step 'the output should contain "0 failures"'
step 'the exit status should be 0'
end
Then /^the example(s)? should( all)? fail/ do |_, _|
step 'the output should not contain "0 failures"'
step 'the exit status should not be 0'
end
Given /active job is available/ do
unless RSpec::Rails::FeatureCheck.has_active_job?
pending "ActiveJob is not available"
end
end
Given /action cable testing is available/ do
unless RSpec::Rails::FeatureCheck.has_action_cable_testing?
pending "Action Cable testing is not available"
end
end
Given /action mailbox is available/ do
unless RSpec::Rails::FeatureCheck.has_action_mailbox?
pending "Action Mailbox is not available"
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/sanity_check_spec.rb | spec/sanity_check_spec.rb | require 'pathname'
RSpec.describe "Verify required rspec dependencies" do
tmp_root = Pathname.new(RSpec::Core::RubyProject.root).join("tmp")
before { FileUtils.mkdir_p tmp_root }
def with_clean_env
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env { yield }
else
Bundler.with_clean_env { yield }
end
end
it "fails when libraries are not required" do
script = tmp_root.join("fail_sanity_check")
File.open(script, "w") do |f|
f.write <<-EOF.gsub(/^\s+\|/, '')
|#!/usr/bin/env ruby
|RSpec::Support.require_rspec_core "project_initializer"
EOF
end
FileUtils.chmod 0777, script
with_clean_env do
expect(`bundle exec #{script} 2>&1`)
.to match(/uninitialized constant RSpec::Support/)
.or match(/undefined method `require_rspec_core' for RSpec::Support:Module/)
.or match(/undefined method `require_rspec_core' for module RSpec::Support/)
.or match(/undefined method 'require_rspec_core' for module RSpec::Support/)
expect($?.exitstatus).to eq(1)
end
end
it "passes when libraries are required", skip: RSpec::Support::Ruby.jruby? do
script = tmp_root.join("pass_sanity_check")
File.open(script, "w") do |f|
f.write <<-EOF.gsub(/^\s+\|/, '')
|#!/usr/bin/env ruby
|require 'rspec/core'
|require 'rspec/support'
|RSpec::Support.require_rspec_core "project_initializer"
EOF
end
FileUtils.chmod 0777, script
with_clean_env do
expect(`bundle exec #{script} 2>&1`).to be_empty
expect($?.exitstatus).to eq(0)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/spec_helper.rb | spec/spec_helper.rb | require 'rails/all'
module RSpecRails
class Application < ::Rails::Application
config.secret_key_base = 'ASecretString'
if defined?(ActionCable)
ActionCable.server.config.cable = { "adapter" => "test" }
ActionCable.server.config.logger =
ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new)
end
end
def self.world
@world
end
def self.world=(world)
@world = world
end
end
I18n.enforce_available_locales = true
require 'rspec/support/spec'
require 'rspec/core/sandbox'
require 'rspec/matchers/fail_matchers'
require 'rspec/rails'
require 'ammeter/init'
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
class RSpec::Core::ExampleGroup
def self.run_all(reporter = nil)
run(reporter || RSpec::Mocks::Mock.new('reporter').as_null_object)
end
end
# This behaviour will become the default in Rails 8, for now it silences a deprecation
if ActiveSupport.respond_to?(:to_time_preserves_timezone)
ActiveSupport.to_time_preserves_timezone = true
end
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# Bring in the failure matchers from rspec-expectations
config.include RSpec::Matchers::FailMatchers
config.expect_with :rspec do |expectations|
# include_chain_clauses_in_custom_matcher_descriptions is removed in RSpec Expectations 4
expectations.include_chain_clauses_in_custom_matcher_descriptions = true if expectations.respond_to?(:include_chain_clauses_in_custom_matcher_descriptions=)
expectations.max_formatted_output_length = 1000
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
mocks.verify_doubled_constant_names = true
end
config.filter_run_when_matching :focus
config.order = :random
Kernel.srand config.seed
# shared_context_metadata_behavior is removed in RSpec 4
config.shared_context_metadata_behavior = :apply_to_host_groups if config.respond_to?(:shared_context_metadata_behavior=)
# Zero monkey patching mode is the default and only mode in RSpec 4
config.disable_monkey_patching! if config.respond_to?(:disable_monkey_patching!)
config.warnings = true
config.raise_on_warning = true
config.raise_errors_for_deprecations!
# Execute a provided block with RSpec global objects (configuration,
# world, current example) reset. This is used to test specs with RSpec.
config.around(:example, :with_isolated_config) do |example|
RSpec::Core::Sandbox.sandboxed do |sandbox_config|
sandbox_config.raise_errors_for_deprecations! # Otherwise, deprecations are swallowed
# If there is an example-within-an-example, we want to make sure the inner
# example does not get a reference to the outer example (the real spec) if
# it calls something like `pending`.
sandbox_config.before(:context) { RSpec.current_example = nil }
RSpec::Rails.initialize_configuration(sandbox_config)
example.run
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/support/generators.rb | spec/support/generators.rb | module RSpec
module Rails
module Specs
module Generators
module Macros
# Tell the generator where to put its output (what it thinks of as
# Rails.root)
def set_default_destination
destination File.expand_path('../../tmp', __dir__)
end
def setup_default_destination
set_default_destination
before { prepare_destination }
end
end
def self.included(klass)
klass.extend(Macros)
klass.include(RSpec::Rails::FeatureCheck)
end
RSpec.shared_examples_for 'a model generator with fixtures' do |name, class_name|
before { run_generator [name, '--fixture'] }
describe 'the spec' do
subject(:model_spec) { file("spec/models/#{name}_spec.rb") }
it 'contains the standard boilerplate' do
expect(model_spec).to contain(/require 'rails_helper'/).and(contain(/^RSpec.describe #{class_name}, #{type_metatag(:model)}/))
end
end
describe 'the fixtures' do
subject(:filename) { file("spec/fixtures/#{name}.yml") }
it 'contains the standard boilerplate' do
expect(filename).to contain(Regexp.new('# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html'))
end
end
end
RSpec.shared_examples_for "a request spec generator" do
describe 'generated with flag `--no-request-specs`' do
before do
run_generator %w[posts --no-request-specs]
end
subject(:request_spec) { file('spec/requests/posts_spec.rb') }
it "does not create the request spec" do
expect(File.exist?(request_spec)).to be false
end
end
describe 'generated with no flags' do
before do
run_generator name
end
subject(:request_spec) { file(spec_file_name) }
context 'When NAME=posts' do
let(:name) { %w[posts] }
let(:spec_file_name) { 'spec/requests/posts_spec.rb' }
it 'contains the standard boilerplate' do
expect(request_spec).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "Posts", #{type_metatag(:request)}/))
.and(contain(/describe "GET \/posts"/))
.and(contain(/get posts_index_path/))
end
end
context 'When NAME=api/posts' do
let(:name) { %w[api/posts] }
let(:spec_file_name) { 'spec/requests/api/posts_spec.rb' }
it 'contains the standard boilerplate' do
expect(request_spec).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "Api::Posts", #{type_metatag(:request)}/))
.and(contain(/describe "GET \/api\/posts"/))
.and(contain(/get api_posts_index_path\n/))
end
end
end
end
end
end
end
end
RSpec.configure do |config|
config.include RSpec::Rails::Specs::Generators, type: :generator
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/support/shared_examples.rb | spec/support/shared_examples.rb | require 'pathname'
RSpec.shared_examples_for "an rspec-rails example group mixin" do |type, *paths|
let(:mixin) { described_class }
def define_group_in(path, group_definition)
path = Pathname(path)
$_new_group = nil
begin
file = path + "whatever_spec.rb"
Dir.mktmpdir("rspec-rails-app-root") do |dir|
Dir.chdir(dir) do
path.mkpath
File.open(file, "w") do |f|
f.write("$_new_group = #{group_definition}")
end
load file
end
end
group = $_new_group
return group
ensure
$_new_group = nil
end
end
it "adds does not add `:type` metadata on inclusion" do
mixin = self.mixin
group = RSpec.describe { include mixin }
expect(group.metadata).not_to include(:type)
end
context 'when `infer_spec_type_from_file_location!` is configured' do
before { RSpec.configuration.infer_spec_type_from_file_location! }
paths.each do |path|
context "for an example group defined in a file in the #{path} directory" do
it "includes itself in the example group" do
group = define_group_in path, "RSpec.describe"
expect(group.included_modules).to include(mixin)
end
it "tags groups in that directory with `type: #{type.inspect}`" do
group = define_group_in path, "RSpec.describe"
expect(group.metadata).to include(type: type)
end
it "allows users to override the type" do
group = define_group_in path, "RSpec.describe 'group', type: :other"
expect(group.metadata).to include(type: :other)
expect(group.included_modules).not_to include(mixin)
end
it "applies configured `before(:context)` hooks with `type: #{type.inspect}` metadata" do
block_run = false
RSpec.configuration.before(:context, type: type) { block_run = true }
group = define_group_in path, "RSpec.describe('group') { it { } }"
group.run(double.as_null_object)
expect(block_run).to eq(true)
end
end
end
it "includes itself in example groups tagged with `type: #{type.inspect}`" do
group = define_group_in "spec/other", "RSpec.describe 'group', type: #{type.inspect}"
expect(group.included_modules).to include(mixin)
end
end
context 'when `infer_spec_type_from_file_location!` is not configured' do
it "includes itself in example groups tagged with `type: #{type.inspect}`" do
group = define_group_in "spec/other", "RSpec.describe 'group', type: #{type.inspect}"
expect(group.included_modules).to include(mixin)
end
paths.each do |path|
context "for an example group defined in a file in the #{path} directory" do
it "does not include itself in the example group" do
group = define_group_in path, "RSpec.describe"
expect(group.included_modules).not_to include(mixin)
end
it "does not tag groups in that directory with `type: #{type.inspect}`" do
group = define_group_in path, "RSpec.describe"
expect(group.metadata).not_to include(:type)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/support/group_failure_formatter.rb | spec/support/group_failure_formatter.rb | module RSpec::Rails::TestSupport
class FailureReporter
def initialize
@exceptions = []
end
attr_reader :exceptions
def example_failed(example)
@exceptions << example.exception
end
def method_missing(name, *_args, &_block)
end
end
def failure_reporter
@failure_reporter ||= FailureReporter.new
end
end
RSpec.configure do |config|
config.include RSpec::Rails::TestSupport
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/support/null_object.rb | spec/support/null_object.rb | class NullObject
private
def method_missing(method, *args, &blk)
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/support/ar_classes.rb | spec/support/ar_classes.rb | ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
module Connections
def self.extended(host)
fields =
{ host.primary_key => "integer PRIMARY KEY AUTOINCREMENT" }
fields.merge!(host.connection_fields) if host.respond_to?(:connection_fields)
host.connection.execute <<-EOSQL
CREATE TABLE #{host.table_name} ( #{fields.map { |column, type| "#{column} #{type}"}.join(", ") })
EOSQL
host.reset_column_information
end
end
class NonActiveRecordModel
extend ActiveModel::Naming
include ActiveModel::Conversion
end
class MockableModel < ActiveRecord::Base
def self.connection_fields
{ associated_model_id: :integer }
end
extend Connections
has_one :associated_model
end
class SubMockableModel < MockableModel
end
class AssociatedModel < ActiveRecord::Base
def self.connection_fields
{ mockable_model_id: :integer, nonexistent_model_id: :integer }
end
extend Connections
belongs_to :mockable_model
belongs_to :nonexistent_model, class_name: "Other"
end
class AlternatePrimaryKeyModel < ActiveRecord::Base
self.primary_key = :my_id
extend Connections
attr_accessor :my_id
end
module Namespaced
class Model < ActiveRecord::Base
def self.connection_fields
{ name: :string }
end
extend Connections
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails_spec.rb | spec/rspec/rails_spec.rb | require 'rspec/support/spec/library_wide_checks'
RSpec.describe "RSpec::Rails" do
include RSpec::Support::WhitespaceChecks
# Pasted from rspec-support lib/rspec/support/spec/library_wide_checks.rb:134
# Easier to do that here than to extract it out
RSpec::Matchers.define :be_well_formed do
match do |actual|
actual.empty?
end
failure_message do |actual|
actual.join("\n")
end
end
it "has no malformed whitespace", :slow do
error_messages = []
`git ls-files -z`.split("\x0").each do |filename|
error_messages << check_for_tab_characters(filename)
error_messages << check_for_extra_spaces(filename)
end
expect(error_messages.compact).to be_well_formed
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/fixture_support_spec.rb | spec/rspec/rails/fixture_support_spec.rb | module RSpec::Rails
RSpec.describe FixtureSupport, :with_isolated_config do
context "with use_transactional_fixtures set to false" do
it "still supports fixture_path/fixture_paths" do
allow(RSpec.configuration).to receive(:use_transactional_fixtures) { false }
group = RSpec::Core::ExampleGroup.describe do
include FixtureSupport
end
expect(group).to respond_to(:fixture_paths)
expect(group).to respond_to(:fixture_paths=)
end
end
context "with use_transactional_tests set to true" do
it "works with #uses_transaction helper" do
group = RSpec::Core::ExampleGroup.describe do
include FixtureSupport
self.use_transactional_tests = true
uses_transaction "doesn't run in transaction"
it "doesn't run in transaction" do
expect(ActiveRecord::Base.connection.transaction_open?).to eq(false)
end
it "runs in transaction" do
expect(ActiveRecord::Base.connection.transaction_open?).to eq(true)
end
end
expect_to_pass(group)
end
end
context "with use_transactional_tests set to false" do
it "does not wrap the test in a transaction" do
allow(RSpec.configuration).to receive(:use_transactional_fixtures) { true }
group = RSpec::Core::ExampleGroup.describe do
include FixtureSupport
self.use_transactional_tests = false
it "doesn't run in transaction" do
expect(ActiveRecord::Base.connection.transaction_open?).to eq(false)
end
end
expect_to_pass(group)
end
end
it "handles namespaced fixtures" do
group = RSpec::Core::ExampleGroup.describe do
include FixtureSupport
fixtures 'namespaced/model'
it 'has the fixture' do
namespaced_model(:one)
end
end
group.fixture_paths = [File.expand_path('../../support/fixtures', __dir__)]
expect_to_pass(group)
end
def expect_to_pass(group)
result = group.run(failure_reporter)
failure_reporter.exceptions.map { |e| raise e }
expect(result).to be true
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/minitest_lifecycle_adapter_spec.rb | spec/rspec/rails/minitest_lifecycle_adapter_spec.rb | RSpec.describe RSpec::Rails::MinitestLifecycleAdapter, :with_isolated_config do
it "invokes minitest lifecycle hooks at the appropriate times" do
invocations = []
example_group = RSpec::Core::ExampleGroup.describe("MinitestHooks") do
include RSpec::Rails::MinitestLifecycleAdapter
define_method(:before_setup) { invocations << :before_setup }
define_method(:after_setup) { invocations << :after_setup }
define_method(:before_teardown) { invocations << :before_teardown }
define_method(:after_teardown) { invocations << :after_teardown }
end
example_group.example("foo") { invocations << :example }
example_group.run(NullObject.new)
expect(invocations).to eq([
:before_setup, :after_setup, :example, :before_teardown, :after_teardown
])
end
it "allows let variables named 'send'" do
run_result = ::RSpec::Core::ExampleGroup.describe do
let(:send) { "WHAT" }
specify { expect(send).to eq "WHAT" }
end.run NullObject.new
expect(run_result).to be true
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/assertion_delegator_spec.rb | spec/rspec/rails/assertion_delegator_spec.rb | RSpec.describe RSpec::Rails::AssertionDelegator do
it "provides a module that delegates assertion methods to an isolated class" do
klass = Class.new {
include RSpec::Rails::AssertionDelegator.new(RSpec::Rails::Assertions)
}
expect(klass.new).to respond_to(:assert)
end
it "delegates back to the including instance for methods the assertion module requires" do
assertions = Module.new {
def has_thing?(thing)
things.include?(thing)
end
}
klass = Class.new {
include RSpec::Rails::AssertionDelegator.new(assertions)
def things
[:a]
end
}
expect(klass.new).to have_thing(:a)
expect(klass.new).not_to have_thing(:b)
end
it "does not delegate method_missing" do
assertions = Module.new {
def method_missing(method, *args)
end
}
klass = Class.new {
include RSpec::Rails::AssertionDelegator.new(assertions)
}
expect { klass.new.abc123 }.to raise_error(NoMethodError)
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/view_spec_methods_spec.rb | spec/rspec/rails/view_spec_methods_spec.rb | module RSpec::Rails
RSpec.describe ViewSpecMethods do
before do
class ::VCSampleClass; end
end
after do
Object.send(:remove_const, :VCSampleClass)
end
describe ".add_extra_params_accessors_to" do
describe "when accessors are not yet defined" do
it "adds them as instance methods" do
ViewSpecMethods.add_to(VCSampleClass)
expect(VCSampleClass.instance_methods.map(&:to_sym)).to(include(:extra_params=))
expect(VCSampleClass.instance_methods.map(&:to_sym)).to(include(:extra_params))
end
describe "the added #extra_params reader" do
it "raises an error when a user tries to mutate it" do
ViewSpecMethods.add_to(VCSampleClass)
expect {
VCSampleClass.new.extra_params[:id] = 4
}.to raise_error(/can't modify frozen/)
end
end
end
describe "when accessors are already defined" do
before do
class ::VCSampleClass
def extra_params; end
def extra_params=; end
end
end
it "does not redefine them" do
ViewSpecMethods.add_to(VCSampleClass)
expect(VCSampleClass.new.extra_params).to be_nil
end
end
end
describe ".remove_extra_params_accessors_from" do
describe "when accessors are defined" do
before do
ViewSpecMethods.add_to(VCSampleClass)
end
it "removes them" do
ViewSpecMethods.remove_from(VCSampleClass)
expect(VCSampleClass.instance_methods).to_not include("extra_params=")
expect(VCSampleClass.instance_methods).to_not include(:extra_params=)
expect(VCSampleClass.instance_methods).to_not include("extra_params")
expect(VCSampleClass.instance_methods).to_not include(:extra_params)
end
end
describe "when accessors are not defined" do
it "does nothing" do
expect {
ViewSpecMethods.remove_from(VCSampleClass)
}.to_not change { VCSampleClass.instance_methods }
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/configuration_spec.rb | spec/rspec/rails/configuration_spec.rb | require 'rspec/support/spec/in_sub_process'
RSpec.describe "Configuration" do
include RSpec::Support::InSubProcess
subject(:config) { RSpec::Core::Configuration.new }
before do
RSpec::Rails.initialize_configuration(config)
end
it "adds 'vendor/' to the backtrace exclusions" do
expect(config.backtrace_exclusion_patterns).to include(/vendor\//)
end
it "adds 'lib/rspec/rails' to the backtrace exclusions" do
expect(
config.backtrace_exclusion_patterns
).to include(%r{lib/rspec/rails})
end
shared_examples_for "adds setting" do |accessor, opts|
opts ||= {}
default_value = opts[:default]
alias_setting = opts[:alias_with]
predicate_method = "#{accessor}?".to_sym
command_method = "#{accessor}=".to_sym
specify "`##{accessor}` is `#{default_value.inspect}` by default" do
expect(config.send(accessor)).to eq default_value
end
specify "`##{predicate_method}` is `#{!!default_value}` by default" do
expect(config.send(predicate_method)).to be !!default_value
end
specify "`##{predicate_method}` is `#{!!default_value}` by default" do
expect(config.send(predicate_method)).to be !!default_value
end
describe "`##{command_method}`" do
it "changes `#{predicate_method}` to the true for a truthy value" do
config.send(command_method, nil)
expect(config.send(predicate_method)).to be false
expect {
config.send(command_method, :a_value)
}.to change { config.send(predicate_method) }.to(true)
end
it "sets `#{accessor}` to the provided value" do
expect {
config.send(command_method, :a_value)
}.to change {
config.send(accessor)
}.from(default_value).to(:a_value)
end
end
if alias_setting
specify "`##{alias_setting}` is an alias for `#{accessor}`" do
expect {
config.send(command_method, :a_value)
}.to change { config.send(alias_setting) }.to(:a_value)
end
end
end
context "adds settings" do
include_examples "adds setting",
:infer_base_class_for_anonymous_controllers,
default: true
include_examples "adds setting",
:use_transactional_fixtures,
alias_with: :use_transactional_examples
include_examples "adds setting", :use_instantiated_fixtures
include_examples "adds setting", :global_fixtures
include_examples "adds setting", :fixture_paths
include_examples "adds setting", :rendering_views
specify "`#render_views?` is false by default" do
expect(config.render_views?).to be false
end
specify "`#render_views` sets `render_views?` to `true`" do
expect {
config.render_views
}.to change { config.render_views? }.to be(true)
end
describe "`#render_views=`" do
it "sets `render_views?` to the truthiness of the provided value" do
expect {
config.render_views = :a_value
}.to change { config.render_views? }.from(false).to(true)
# this is repeated to put the value back to false
expect {
config.render_views = false
}.to change { config.render_views? }.from(true).to(false)
end
end
end
specify "#filter_rails_from_backtrace! adds exclusion patterns for rails gems" do
config.filter_rails_from_backtrace!
gems = %w[
actionmailer
actionpack
actionview
activemodel
activerecord
activesupport
activejob
]
exclusions = config.backtrace_exclusion_patterns.map(&:to_s)
aggregate_failures do
gems.each { |gem| expect(exclusions).to include(/#{gem}/) }
end
end
describe "#infer_spec_type_from_file_location!", :with_isolated_config do
def in_inferring_type_from_location_environment
in_sub_process do
RSpec.configuration.infer_spec_type_from_file_location!
yield
end
end
shared_examples_for "infers type from location" do |type, location|
it "sets the type to `#{type.inspect}` for file path `#{location}`" do
in_inferring_type_from_location_environment do
allow(RSpec::Core::Metadata).to receive(:relative_path).and_return(
"./#{location}/foos_spec.rb"
)
group = RSpec.describe("Arbitrary Description")
expect(group.metadata).to include(type: type)
end
end
end
include_examples "infers type from location",
:controller,
"spec/controllers"
include_examples "infers type from location", :helper, "spec/helpers"
include_examples "infers type from location", :mailer, "spec/mailers"
include_examples "infers type from location", :model, "spec/models"
include_examples "infers type from location", :request, "spec/requests"
include_examples "infers type from location", :request, "spec/integration"
include_examples "infers type from location", :request, "spec/api"
include_examples "infers type from location", :routing, "spec/routing"
include_examples "infers type from location", :view, "spec/views"
include_examples "infers type from location", :feature, "spec/features"
end
it "fixture support is included with metadata `:use_fixtures`" do
RSpec.configuration.global_fixtures = [:foo]
RSpec.configuration.fixture_paths = ["custom/path"]
group = RSpec.describe("Arbitrary Description", :use_fixtures)
expect(group.fixture_paths).to eq(["custom/path"])
expect(group.new.respond_to?(:foo, true)).to be(true)
end
it "fixture support is included with metadata `:use_fixtures` and fixture_paths configured" do
in_sub_process do
RSpec.configuration.global_fixtures = [:foo]
RSpec.configuration.fixture_paths = ["custom/path", "other/custom/path"]
group = RSpec.describe("Arbitrary Description", :use_fixtures)
expect(group).to respond_to(:fixture_paths)
expect(group.fixture_paths).to eq(["custom/path", "other/custom/path"])
expect(group.new.respond_to?(:foo, true)).to be(true)
end
end
it "metadata `type: :controller` sets up controller example groups" do
a_controller_class = Class.new
stub_const "SomeController", a_controller_class
group = RSpec.describe(SomeController, type: :controller)
expect(group.controller_class).to be(a_controller_class)
expect(group.new).to be_a(RSpec::Rails::ControllerExampleGroup)
end
it "metadata `type: :helper` sets up helper example groups" do
a_helper_module = Module.new
stub_const "SomeHelper", a_helper_module
group = RSpec.describe(SomeHelper, type: :helper)
expect(
group.determine_default_helper_class(:ignored)
).to be(a_helper_module)
expect(group.new).to be_a(RSpec::Rails::HelperExampleGroup)
end
it "metadata `type: :model` sets up model example groups" do
a_model_class = Class.new
stub_const "SomeModel", a_model_class
group = RSpec.describe(SomeModel, type: :model)
expect(group.new).to be_a(RSpec::Rails::ModelExampleGroup)
end
it "metadata `type: :request` sets up request example groups" do
a_rails_app = double("Rails application")
the_rails_module = Module.new {
def self.version; end
def self.application; end
}
allow(the_rails_module).to receive(:application) { a_rails_app }
version = ::Rails::VERSION
stub_const "Rails", the_rails_module
stub_const 'Rails::VERSION', version
group = RSpec.describe("Some Request API", type: :request)
expect(group.new.app).to be(a_rails_app)
expect(group.new).to be_a(RSpec::Rails::RequestExampleGroup)
end
it "metadata `type: :routing` sets up routing example groups" do
a_controller_class = Class.new
stub_const "SomeController", a_controller_class
group = RSpec.describe(SomeController, type: :routing)
expect(group).to respond_to(:routes)
expect(group.new).to be_a(RSpec::Rails::RoutingExampleGroup)
end
it "metadata `type: :view` sets up view example groups" do
a_helper_module = Module.new
stub_const "SomeControllerHelper", a_helper_module
group = RSpec.describe("some_controller/action.html.erb", type: :view)
expect(group._default_helper).to be(a_helper_module)
expect(group.new).to be_a(RSpec::Rails::ViewExampleGroup)
end
it "metadata `type: :feature` sets up feature example groups" do
a_rails_app = double("Rails application")
the_rails_module = Module.new {
def self.version; end
def self.application; end
}
allow(the_rails_module).to receive(:application) { a_rails_app }
version = ::Rails::VERSION
stub_const "Rails", the_rails_module
stub_const 'Rails::VERSION', version
group = RSpec.describe("Some feature description", type: :feature)
example = group.new
expect(example).to respond_to(:visit)
expect(example).to be_a(RSpec::Rails::FeatureExampleGroup)
end
if defined?(ActionMailer)
it "metadata `type: :mailer` sets up mailer example groups" do
a_mailer_class = Class.new
stub_const "SomeMailer", a_mailer_class
group = RSpec.describe(SomeMailer, type: :mailer)
expect(group.mailer_class).to be(a_mailer_class)
expect(group.new).to be_a(RSpec::Rails::MailerExampleGroup)
end
describe 'clears ActionMailer::Base::Deliveries after each example' do
let(:mailer) do
Class.new(ActionMailer::Base) do
default from: 'from@example.com'
def welcome(to:)
mail(to: to, subject: 'subject', body: render(inline: "Hello", layout: false))
end
end
end
before do
ActionMailer::Base.delivery_method = :test
end
it 'only has deliveries from this test (e.g. from email@example.com)' do
mailer.welcome(to: 'email@example.com').deliver_now
expect(ActionMailer::Base.deliveries.map(&:to).flatten.sort).to eq(['email@example.com'])
end
it 'only has deliveries from this test (e.g. from email_2@example.com)' do
mailer.welcome(to: 'email_2@example.com').deliver_now
expect(ActionMailer::Base.deliveries.map(&:to).flatten.sort).to eq(['email_2@example.com'])
end
end
end
it "has a default #file_fixture_path of 'spec/fixtures/files'" do
expect(config.file_fixture_path).to eq("spec/fixtures/files")
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/active_record_spec.rb | spec/rspec/rails/active_record_spec.rb | RSpec.describe "ActiveRecord support" do
around do |ex|
old_value = RSpec::Mocks.configuration.verify_partial_doubles?
ex.run
RSpec::Mocks.configuration.verify_partial_doubles = old_value
end
RSpec.shared_examples_for "stubbing ActiveRecord::Base" do
it "allows you to stub `ActiveRecord::Base`" do
allow(ActiveRecord::Base).to receive(:inspect).and_return("stubbed inspect")
expect(ActiveRecord::Base.inspect).to eq "stubbed inspect"
end
end
RSpec.shared_examples_for "stubbing abstract classes" do
it "allows you to stub abstract classes" do
klass = Class.new(ActiveRecord::Base) do
self.abstract_class = true
end
allow(klass).to receive(:find).and_return("stubbed find")
expect(klass.find(1)).to eq "stubbed find"
end
end
context "with partial double verification enabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = true
end
include_examples "stubbing ActiveRecord::Base"
include_examples "stubbing abstract classes"
end
context "with partial double verification disabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = false
end
include_examples "stubbing ActiveRecord::Base"
include_examples "stubbing abstract classes"
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/assertion_adapter_spec.rb | spec/rspec/rails/assertion_adapter_spec.rb | RSpec.describe RSpec::Rails::MinitestAssertionAdapter do
include RSpec::Rails::MinitestAssertionAdapter
RSpec::Rails::Assertions.public_instance_methods.select { |m| m.to_s =~ /^(assert|flunk|refute)/ }.each do |m|
if m.to_s == "assert_equal"
it "exposes #{m} to host examples" do
assert_equal 3, 3
expect do
assert_equal 3, 4
end.to raise_error(ActiveSupport::TestCase::Assertion)
end
else
it "exposes #{m} to host examples" do
expect(methods).to include(m)
end
end
end
it "does not expose internal methods of Minitest" do
expect(methods).not_to include("_assertions")
end
it "does not expose Minitest's message method" do
expect(methods).not_to include("message")
end
it 'does not leak TestUnit specific methods into the AssertionDelegator' do
expect(methods).to_not include(:build_message)
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/setup_and_teardown_adapter_spec.rb | spec/rspec/rails/setup_and_teardown_adapter_spec.rb | RSpec.describe RSpec::Rails::SetupAndTeardownAdapter, :with_isolated_config do
describe ".setup" do
it "registers before hooks in the order setup is received" do
group = RSpec::Core::ExampleGroup.describe do
include RSpec::Rails::SetupAndTeardownAdapter
def self.foo; "foo"; end
def self.bar; "bar"; end
end
expect(group).to receive(:before).ordered { |&block| expect(block.call).to eq "foo" }
expect(group).to receive(:before).ordered { |&block| expect(block.call).to eq "bar" }
expect(group).to receive(:before).ordered { |&block| expect(block.call).to eq "baz" }
group.setup :foo
group.setup :bar
group.setup { "baz" }
end
it "registers prepend_before hooks for the Rails' setup methods" do
group = RSpec::Core::ExampleGroup.describe do
include RSpec::Rails::SetupAndTeardownAdapter
def self.setup_fixtures; "setup fixtures" end
def self.setup_controller_request_and_response; "setup controller" end
end
expect(group).to receive(:prepend_before) { |&block| expect(block.call).to eq "setup fixtures" }
expect(group).to receive(:prepend_before) { |&block| expect(block.call).to eq "setup controller" }
group.setup :setup_fixtures
group.setup :setup_controller_request_and_response
end
it "registers teardown hooks in the order setup is received" do
group = RSpec::Core::ExampleGroup.describe do
include RSpec::Rails::SetupAndTeardownAdapter
def self.foo; "foo"; end
def self.bar; "bar"; end
end
expect(group).to receive(:after).ordered { |&block| expect(block.call).to eq "foo" }
expect(group).to receive(:after).ordered { |&block| expect(block.call).to eq "bar" }
expect(group).to receive(:after).ordered { |&block| expect(block.call).to eq "baz" }
group.teardown :foo
group.teardown :bar
group.teardown { "baz" }
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/active_model_spec.rb | spec/rspec/rails/active_model_spec.rb | RSpec.describe "ActiveModel support" do
around do |ex|
old_value = RSpec::Mocks.configuration.verify_partial_doubles?
ex.run
RSpec::Mocks.configuration.verify_partial_doubles = old_value
end
RSpec.shared_examples_for "stubbing ActiveModel" do
before do
stub_const 'ActiveRecord' unless defined?(ActiveRecord)
end
it "allows you to stub `ActiveModel`" do
allow(ActiveModel).to receive(:inspect).and_return("stubbed inspect")
expect(ActiveModel.inspect).to eq "stubbed inspect"
end
it 'allows you to stub instances of `ActiveModel`' do
klass = Class.new do
include ActiveModel::AttributeMethods
attr_accessor :name
end
model = klass.new
allow(model).to receive(:name) { 'stubbed name' }
expect(model.name).to eq 'stubbed name'
end
end
context "with partial double verification enabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = true
end
include_examples "stubbing ActiveModel"
end
context "with partial double verification disabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = false
end
include_examples "stubbing ActiveModel"
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/fixture_file_upload_support_spec.rb | spec/rspec/rails/fixture_file_upload_support_spec.rb | module RSpec::Rails
RSpec.describe FixtureFileUploadSupport, :with_isolated_config do
context 'with fixture paths set in config' do
it 'resolves fixture file' do
RSpec.configuration.fixture_paths = [File.dirname(__FILE__)]
expect_to_pass fixture_file_upload_resolved('fixture_file_upload_support_spec.rb')
end
it 'resolves supports `Pathname` objects' do
RSpec.configuration.fixture_paths = [Pathname(File.dirname(__FILE__))]
expect_to_pass fixture_file_upload_resolved('fixture_file_upload_support_spec.rb')
end
end
context 'with fixture paths set in spec' do
it 'resolves fixture file' do
expect_to_pass fixture_file_upload_resolved('fixture_file_upload_support_spec.rb', File.dirname(__FILE__))
end
end
context 'with fixture paths not set' do
it 'resolves fixture using relative path' do
RSpec.configuration.fixture_paths = []
expect_to_pass fixture_file_upload_resolved('spec/rspec/rails/fixture_file_upload_support_spec.rb')
end
end
def expect_to_pass(group)
result = group.run(failure_reporter)
failure_reporter.exceptions.map { |e| raise e }
expect(result).to be true
end
def fixture_file_upload_resolved(fixture_name, file_fixture_path = nil)
RSpec::Core::ExampleGroup.describe do
include RSpec::Rails::FixtureFileUploadSupport
self.file_fixture_path = file_fixture_path
it 'supports fixture file upload' do
file = fixture_file_upload(fixture_name)
expect(file.read).to match(/describe FixtureFileUploadSupport/im)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/view_rendering_spec.rb | spec/rspec/rails/view_rendering_spec.rb | module RSpec::Rails
RSpec.describe ViewRendering, :with_isolated_config do
let(:group) do
RSpec::Core::ExampleGroup.describe do
def controller
ActionController::Base.new
end
include ViewRendering
end
end
context "default" do
context "ActionController::Base" do
it "does not render views" do
expect(group.new.render_views?).to be_falsey
end
it "does not render views in a nested group" do
expect(group.describe.new.render_views?).to be_falsey
end
end
context "ActionController::Metal" do
it "renders views" do
group.new.tap do |example|
def example.controller
ActionController::Metal.new
end
expect(example.render_views?).to be_truthy
end
end
end
end
describe "#render_views" do
context "with no args" do
it "tells examples to render views" do
group.render_views
expect(group.new.render_views?).to be_truthy
end
end
context "with true" do
it "tells examples to render views" do
group.render_views true
expect(group.new.render_views?).to be_truthy
end
end
context "with false" do
it "tells examples not to render views" do
group.render_views false
expect(group.new.render_views?).to be_falsey
end
it "overrides the global config if render_views is enabled there" do
allow(RSpec.configuration).to receive(:render_views?).and_return true
group.render_views false
expect(group.new.render_views?).to be_falsey
end
end
it 'propagates to examples in nested groups properly' do
value = :unset
group.class_exec do
render_views
describe "nested" do
it { value = render_views? }
end
end.run(double.as_null_object)
expect(value).to eq(true)
end
context "in a nested group" do
let(:nested_group) do
group.describe
end
context "with no args" do
it "tells examples to render views" do
nested_group.render_views
expect(nested_group.new.render_views?).to be_truthy
end
end
context "with true" do
it "tells examples to render views" do
nested_group.render_views true
expect(nested_group.new.render_views?).to be_truthy
end
end
context "with false" do
it "tells examples not to render views" do
nested_group.render_views false
expect(nested_group.new.render_views?).to be_falsey
end
end
it "leaves the parent group as/is" do
group.render_views
nested_group.render_views false
expect(group.new.render_views?).to be_truthy
end
it "overrides the value inherited from the parent group" do
group.render_views
nested_group.render_views false
expect(nested_group.new.render_views?).to be_falsey
end
it "passes override to children" do
group.render_views
nested_group.render_views false
expect(nested_group.describe.new.render_views?).to be_falsey
end
end
end
context 'when render_views? is false' do
let(:controller) { ActionController::Base.new }
before { controller.extend(ViewRendering::EmptyTemplates) }
it 'supports manipulating view paths' do
controller.prepend_view_path 'app/views'
controller.append_view_path 'app/others'
expect(controller.view_paths.map(&:to_s)).to match_paths 'app/views', 'app/others'
end
it 'supports manipulating view paths with arrays' do
controller.prepend_view_path ['app/views', 'app/legacy_views']
controller.append_view_path ['app/others', 'app/more_views']
expect(controller.view_paths.map(&:to_s)).to match_paths 'app/views', 'app/legacy_views', 'app/others', 'app/more_views'
end
it 'supports manipulating view paths with resolvers' do
expect {
controller.prepend_view_path ActionView::Resolver.new
controller.append_view_path ActionView::Resolver.new
}.to_not raise_error
end
context 'with empty template resolver' do
class CustomResolver < ActionView::Resolver
def custom_method
true
end
end
it "works with custom resolvers" do
custom_method_called = false
ActionController::Base.view_paths = ActionView::PathSet.new([CustomResolver.new])
group.class_exec do
describe "example" do
it do
custom_method_called = ActionController::Base.view_paths.first.custom_method
end
end
end.run(double.as_null_object)
expect(custom_method_called).to eq(true)
end
it "works with strings" do
decorated = false
ActionController::Base.view_paths = ActionView::PathSet.new(['app/views', 'app/legacy_views'])
group.class_exec do
describe "example" do
it do
decorated = ActionController::Base.view_paths.all? { |resolver| resolver.is_a?(ViewRendering::EmptyTemplateResolver::ResolverDecorator) }
end
end
end.run(double.as_null_object)
expect(decorated).to eq(true)
end
end
def match_paths(*paths)
eq paths.map { |path| File.expand_path path }
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/view_example_group_spec.rb | spec/rspec/rails/example/view_example_group_spec.rb | require 'support/group_failure_formatter'
module RSpec::Rails
RSpec.describe ViewExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :view,
'./spec/views/', '.\\spec\\views\\'
describe 'automatic inclusion of helpers' do
module ::ThingsHelper; end
module ::Namespaced; module ThingsHelper; end; end
it 'includes the helper with the same name' do
group = RSpec::Core::ExampleGroup.describe('things/show.html.erb') do
def self.helper(*); end # Stub method
end
allow(group).to receive(:helper)
expect(group).to receive(:helper).with(ThingsHelper)
group.class_exec do
include ViewExampleGroup
end
end
it 'includes the namespaced helper with the same name' do
group = RSpec::Core::ExampleGroup.describe('namespaced/things/show.html.erb') do
def self.helper(*); end # Stub method
end
allow(group).to receive(:helper)
expect(group).to receive(:helper).with(Namespaced::ThingsHelper)
group.class_exec do
include ViewExampleGroup
end
end
it 'operates normally when no helper with the same name exists' do
raise 'unexpected constant found' if Object.const_defined?('ClocksHelper')
expect {
RSpec::Core::ExampleGroup.describe 'clocks/show.html.erb' do
include ViewExampleGroup
end
}.not_to raise_error
end
it 'operates normally when the view has no path and there is a Helper class defined' do
class ::Helper; end
expect {
RSpec::Core::ExampleGroup.describe 'show.html.erb' do
include ViewExampleGroup
end
}.not_to raise_error
end
context 'application helper exists' do
before do
unless Object.const_defined? 'ApplicationHelper'
module ::ApplicationHelper; end
@application_helper_defined = true
end
end
after do
if @application_helper_defined
Object.__send__ :remove_const, 'ApplicationHelper'
end
end
it 'includes the application helper' do
group = RSpec::Core::ExampleGroup.describe('bars/new.html.erb') do
def self.helper(*); end # Stub method
end
allow(group).to receive(:helper)
expect(group).to receive(:helper).with(ApplicationHelper)
group.class_exec do
include ViewExampleGroup
end
end
end
context 'no application helper exists' do
before do
if Object.const_defined? 'ApplicationHelper'
@application_helper = ApplicationHelper
Object.__send__ :remove_const, 'ApplicationHelper'
end
end
after do
if defined?(@application_helper)
ApplicationHelper = @application_helper
end
end
it 'operates normally' do
expect {
RSpec::Core::ExampleGroup.describe 'foos/edit.html.erb' do
include ViewExampleGroup
end
}.not_to raise_error
end
end
end
describe "routes helpers collides with asset helpers" do
let(:view_spec) do
Class.new do
include ActionView::Helpers::AssetTagHelper
include ViewExampleGroup::ExampleMethods
end.new
end
let(:test_routes) do
ActionDispatch::Routing::RouteSet.new.tap do |routes|
routes.draw { resources :images }
end
end
it "uses routes helpers" do
allow(::Rails.application).to receive(:routes).and_return(test_routes)
expect(view_spec.image_path(double(to_param: "42")))
.to eq "/images/42"
end
end
describe "#render" do
let(:view_spec) do
Class.new do
local = Module.new do
def received
@received ||= []
end
def render(options = {}, local_assigns = {}, &block)
received << [options, local_assigns, block]
end
def _assigns
{}
end
end
include local
def _default_file_to_render; end # Stub method
include ViewExampleGroup::ExampleMethods
end.new
end
context "given no input" do
it "sends render(:template => (described file)) to the view" do
allow(view_spec).to receive(:_default_file_to_render) { "widgets/new" }
view_spec.render
expect(view_spec.received.first).to eq([{ template: "widgets/new" }, {}, nil])
end
it "converts the filename components into render options" do
allow(view_spec).to receive(:_default_file_to_render) { "widgets/new.en.html.erb" }
view_spec.render
expect(view_spec.received.first).to eq([{ template: "widgets/new", locales: [:en], formats: [:html], handlers: [:erb] }, {}, nil])
end
it "converts the filename with variant into render options" do
allow(view_spec).to receive(:_default_file_to_render) { "widgets/new.en.html+fancy.erb" }
view_spec.render
expect(view_spec.received.first).to eq([{ template: "widgets/new", locales: [:en], formats: [:html], handlers: [:erb], variants: [:fancy] }, {}, nil])
end
it "converts the filename without format into render options" do
allow(view_spec).to receive(:_default_file_to_render) { "widgets/new.en.erb" }
view_spec.render
expect(view_spec.received.first).to eq([{ template: "widgets/new", locales: [:en], handlers: [:erb] }, {}, nil])
end
end
context "given a string" do
it "sends string as the first arg to render" do
view_spec.render('arbitrary/path')
expect(view_spec.received.first).to eq(["arbitrary/path", {}, nil])
end
end
context "given a hash" do
it "sends the hash as the first arg to render" do
view_spec.render(foo: 'bar')
expect(view_spec.received.first).to eq([{ foo: "bar" }, {}, nil])
end
end
end
describe '#params' do
let(:view_spec) do
Class.new do
include ViewExampleGroup::ExampleMethods
def controller
@controller ||= Struct.new(:params).new(nil)
end
end.new
end
it 'delegates to the controller' do
expect(view_spec.controller).to receive(:params).and_return({})
view_spec.params[:foo] = 1
end
end
describe "#_controller_path" do
let(:view_spec) do
Class.new do
include ViewExampleGroup::ExampleMethods
def _default_file_to_render; end
end.new
end
context "with a common _default_file_to_render" do
it "it returns the directory" do
allow(view_spec).to receive(:_default_file_to_render)
.and_return("things/new.html.erb")
expect(view_spec.__send__(:_controller_path))
.to eq("things")
end
end
context "with a nested _default_file_to_render" do
it "it returns the directory path" do
allow(view_spec).to receive(:_default_file_to_render)
.and_return("admin/things/new.html.erb")
expect(view_spec.__send__(:_controller_path))
.to eq("admin/things")
end
end
end
describe "#view" do
let(:view_spec) do
Class.new do
def _view; end # Stub method
include ViewExampleGroup::ExampleMethods
end.new
end
it "delegates to _view" do
view = double("view")
allow(view_spec).to receive(:_view) { view }
expect(view_spec.view).to eq(view)
end
# Regression test from rspec/rspec-rails#833
it 'is accessible to configuration-level hooks' do
run_count = 0
RSpec.configuration.before(:each, type: :view) do
# `view` is provided from the view example type, and serves to
# demonstrate this hook is run in the correct context.
allow(view).to receive(:render) { :value }
run_count += 1
end
group = RSpec::Core::ExampleGroup.describe 'a view', type: :view do
specify { expect(view.render).to eq(:value) }
end
group.run(failure_reporter)
expect(failure_reporter.exceptions).to eq []
expect(run_count).to eq 1
end
end
describe "#template" do
let(:view_spec) do
Class.new do
include ViewExampleGroup::ExampleMethods
def _view; end
end.new
end
before { allow(RSpec).to receive(:deprecate) }
it "is deprecated" do
expect(RSpec).to receive(:deprecate)
view_spec.template
end
it "delegates to #view" do
expect(view_spec).to receive(:view)
view_spec.template
end
end
describe '#stub_template' do
let(:view_spec_group) do
RSpec.describe "a view spec" do
include ::RSpec::Rails::ViewExampleGroup
end
end
it 'prepends an ActionView::FixtureResolver to the view path' do
result = :not_loaded
view_spec_group.specify do
stub_template('some_path/some_template' => 'stubbed-contents')
result = view.view_paths.first
end
view_spec_group.run
expect(result).to be_instance_of(ActionView::FixtureResolver)
data = result.respond_to?(:data) ? result.data : result.hash
expect(data).to eq('some_path/some_template' => 'stubbed-contents')
end
it 'caches FixtureResolver instances between examples' do
example_one_view_paths = :not_set
example_two_view_paths = :not_set
view_spec_group.specify do
stub_template('some_path/some_template' => 'stubbed-contents')
example_one_view_paths = view.view_paths
end
view_spec_group.specify do
stub_template('some_path/some_template' => 'stubbed-contents')
example_two_view_paths = view.view_paths
end
view_spec_group.run
expect(example_one_view_paths.first).to eq(example_two_view_paths.first)
end
it 'caches FixtureResolver instances between example groups' do
example_one_view_paths = :not_set
example_two_view_paths = :not_set
RSpec.describe "a view spec" do
include ::RSpec::Rails::ViewExampleGroup
specify do
stub_template('some_path/some_template' => 'stubbed-contents')
example_one_view_paths = view.view_paths
end
end.run
RSpec.describe "another view spec" do
include ::RSpec::Rails::ViewExampleGroup
specify do
stub_template('some_path/some_template' => 'stubbed-contents')
example_two_view_paths = view.view_paths
end
end.run
expect(example_one_view_paths.first).to eq(example_two_view_paths.first)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/system_example_group_spec.rb | spec/rspec/rails/example/system_example_group_spec.rb | module RSpec::Rails
RSpec.describe SystemExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :system,
'./spec/system/', '.\\spec\\system\\'
describe '#method_name' do
it 'converts special characters to underscores' do
group = RSpec::Core::ExampleGroup.describe ActionPack do
include SystemExampleGroup
end
SystemExampleGroup::CHARS_TO_TRANSLATE.each do |char|
example = group.new
example_class_mock = double('name' => "method#{char}name")
allow(example).to receive(:class).and_return(example_class_mock)
expect(example.send(:method_name)).to start_with('method_name')
end
end
it "handles long method names which include unicode characters" do
group =
RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
end
example = group.new
allow(example.class).to receive(:name) { "really long unicode example name - #{'あ'*100}" }
expect(example.send(:method_name).bytesize).to be <= 210
end
end
describe '#driver' do
it 'uses :selenium_chrome_headless driver by default' do
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
end
example = group.new
group.hooks.run(:before, :example, example)
expect(Capybara.current_driver).to eq :selenium_chrome_headless
end
it 'sets :rack_test driver using by before_action' do
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
driven_by(:rack_test)
end
end
example = group.new
group.hooks.run(:before, :example, example)
expect(Capybara.current_driver).to eq :rack_test
end
it 'calls :driven_by method only once' do
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
driven_by(:rack_test)
end
end
example = group.new
allow(example).to receive(:driven_by).and_call_original
group.hooks.run(:before, :example, example)
expect(example).to have_received(:driven_by).once
end
it 'calls :served_by method only once' do
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
served_by(host: 'rails', port: 8080)
end
end
example = group.new
allow(example).to receive(:served_by).and_call_original
group.hooks.run(:before, :example, example)
expect(example).to have_received(:served_by).once
end
end
describe '#after' do
it 'sets the :extra_failure_lines metadata to an array of STDOUT lines' do
allow(Capybara::Session).to receive(:instance_created?).and_return(true)
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
driven_by(:selenium)
end
def take_screenshot
puts 'line 1'
puts 'line 2'
end
end
example = group.it('fails') { fail }
group.run
expect(example.metadata[:extra_failure_lines]).to eq(["line 1\n", "line 2\n"])
end
end
describe '#take_screenshot' do
it 'handles Rails calling metadata' do
allow(Capybara::Session).to receive(:instance_created?).and_return(true)
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
driven_by(:selenium)
end
def page
instance_double(Capybara::Session, save_screenshot: nil)
end
end
example = group.it('fails') { raise }
group.run
expect(example.metadata[:execution_result].exception).to be_a RuntimeError
end
end
describe '#metadata' do
let(:group) do
RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
end
end
it 'fakes out the rails expected method' do
example = group.it('does nothing') {
metadata[:failure_screenshot_path] = :value
expect(metadata[:failure_screenshot_path]).to eq(:value)
}
group.run
expect(example.execution_result.status).to eq :passed
end
it 'still raises correctly if you use it for something else' do
examples = []
examples << group.it('fails nothing') { metadata[:other] = :value }
examples << group.it('fails nothing') { metadata[:other] }
examples << group.it('fails nothing') { metadata.key?(:any) }
group.run
expect(examples.map(&:execution_result)).to all have_attributes status: :failed
end
end
describe "hook order" do
it 'calls Capybara.reset_sessions (TestUnit after_teardown) after any after hooks' do
calls_in_order = []
allow(Capybara).to receive(:reset_sessions!) { calls_in_order << :reset_sessions! }
group = RSpec::Core::ExampleGroup.describe do
include SystemExampleGroup
before do
driven_by(:selenium)
end
after do
calls_in_order << :after_hook
end
append_after do
calls_in_order << :append_after_hook
end
around do |example|
example.run
calls_in_order << :around_hook_after_example
end
end
group.it('works') { }
group.run
expect(calls_in_order).to eq([:after_hook, :append_after_hook, :around_hook_after_example, :reset_sessions!])
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/controller_example_group_spec.rb | spec/rspec/rails/example/controller_example_group_spec.rb | class ::ApplicationController
def self.abstract?; false; end
end
module RSpec::Rails
RSpec.describe ControllerExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :controller,
'./spec/controllers/', '.\\spec\\controllers\\'
def group_for(klass)
RSpec::Core::ExampleGroup.describe klass do
include ControllerExampleGroup
end
end
let(:group) { group_for ApplicationController }
it "includes routing matchers" do
expect(group.included_modules).to include(RSpec::Rails::Matchers::RoutingMatchers)
end
it "handles methods invoked via `method_missing` that use keywords" do
group =
RSpec::Core::ExampleGroup.describe ApplicationController do
def a_method(value:); value; end
def method_missing(_name, *_args, **kwargs, &_block); a_method(**kwargs); end
# This example requires prepend so that the `method_missing` definition
# from `ControllerExampleGroup` bubbles up to our artificial one, in reality
# this is likely to be either an internal RSpec dispatch or one from a 3rd
# party gem.
prepend ControllerExampleGroup
end
example = group.new
expect(example.call_a_method(value: :value)).to eq :value
end
context "with implicit subject" do
it "uses the controller as the subject" do
controller = double('controller')
example = group.new
allow(example).to receive_messages(controller: controller)
expect(example.subject).to eq(controller)
end
it "doesn't cause let definition priority to be changed" do
# before #738 implicit subject definition for controllers caused
# external methods to take precedence over our let definitions
mod = Module.new do
def my_helper
"other_value"
end
end
ActiveRecord::Base.include mod
group.class_exec do
let(:my_helper) { "my_value" }
end
expect(group.new.my_helper).to eq "my_value"
end
end
context "with explicit subject" do
it "uses the specified subject instead of the controller" do
sub_group = group.describe do
subject { 'explicit' }
end
example = sub_group.new
expect(example.subject).to eq('explicit')
end
end
describe "#controller" do
let(:controller) { double('controller') }
let(:example) { group.new }
let(:routes) do
with_isolated_stderr do
routes = ActionDispatch::Routing::RouteSet.new
routes.draw { resources :foos }
routes
end
end
before do
group.class_exec do
controller(Class.new) { }
end
allow(controller).to receive(:foos_url).and_return('http://test.host/foos')
allow(example).to receive_messages(controller: controller)
example.instance_variable_set(:@orig_routes, routes)
end
it "delegates named route helpers to the underlying controller" do
expect(example.foos_url).to eq('http://test.host/foos')
end
it "calls NamedRouteCollection#route_defined? when it checks that given route is defined or not" do
expect(routes.named_routes).to receive(:route_defined?).and_return(true)
example.foos_url
end
end
describe "#bypass_rescue" do
it "overrides the rescue_with_handler method on the controller to raise submitted error" do
example = group.new
example.instance_variable_set("@controller", Class.new { def rescue_with_handler(e); end }.new)
example.bypass_rescue
expect do
example.controller.rescue_with_handler(RuntimeError.new("foo"))
end.to raise_error("foo")
end
end
describe "with inferred anonymous controller" do
let(:anonymous_klass) { Class.new }
let(:group) { group_for(anonymous_klass) }
it "defaults to inferring anonymous controller class" do
expect(RSpec.configuration.infer_base_class_for_anonymous_controllers).to be_truthy
end
context "when infer_base_class_for_anonymous_controllers is true" do
around(:example) do |ex|
RSpec.configuration.infer_base_class_for_anonymous_controllers = true
ex.run
end
it "infers the anonymous controller class" do
group.controller { }
expect(group.controller_class.superclass).to eq(anonymous_klass)
end
it "infers the anonymous controller class when no ApplicationController is present" do
hide_const '::ApplicationController'
group.controller { }
expect(group.controller_class.superclass).to eq(anonymous_klass)
end
end
context "when infer_base_class_for_anonymous_controllers is false" do
around(:example) do |ex|
RSpec.configuration.infer_base_class_for_anonymous_controllers = false
ex.run
end
it "sets the anonymous controller class to ApplicationController" do
group.controller { }
expect(group.controller_class.superclass).to eq(ApplicationController)
end
it "sets the anonymous controller class to ActiveController::Base when no ApplicationController is present" do
hide_const '::ApplicationController'
group.controller { }
expect(group.controller_class.superclass).to eq(ActionController::Base)
end
end
end
describe "controller name" do
let(:controller_class) { group.controller_class }
it "sets the name as AnonymousController if it's anonymous" do
group.controller { }
expect(controller_class.name).to eq "AnonymousController"
end
it "sets the name according to defined controller if it is not anonymous" do
stub_const "FoosController", Class.new(::ApplicationController)
group.controller(FoosController) { }
expect(controller_class.name).to eq "FoosController"
end
it "sets name as AnonymousController if defined as ApplicationController" do
group.controller(ApplicationController) { }
expect(controller_class.name).to eq "AnonymousController"
end
it "sets name as AnonymousController if the controller is abstract" do
abstract_controller = Class.new(::ApplicationController)
def abstract_controller.abstract?; true; end
group.controller(abstract_controller) { }
expect(controller_class.name).to eq "AnonymousController"
end
it "sets name as AnonymousController if it inherits outer group's anonymous controller" do
outer_group = group_for ApplicationController
outer_group.controller { }
inner_group = group.describe { }
inner_group.controller(outer_group.controller_class) { }
expect(inner_group.controller_class.name).to eq "AnonymousController"
end
end
context "in a namespace" do
describe "controller name" do
let(:controller_class) { group.controller_class }
it "sets the name according to the defined controller namespace if it is not anonymous" do
stub_const "A::B::FoosController", Class.new(::ApplicationController)
group.controller(A::B::FoosController) { }
expect(controller_class.name).to eq "A::B::FoosController"
end
it "sets the name as 'AnonymousController' if the controller is abstract" do
abstract_controller = Class.new(::ApplicationController)
def abstract_controller.abstract?; true; end
stub_const "A::B::FoosController", abstract_controller
group.controller(A::B::FoosController) { }
expect(controller_class.name).to eq "AnonymousController"
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/channel_example_group_spec.rb | spec/rspec/rails/example/channel_example_group_spec.rb | require "rspec/rails/feature_check"
module RSpec::Rails
RSpec.describe ChannelExampleGroup, :with_isolated_config do
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
it_behaves_like "an rspec-rails example group mixin", :channel,
'./spec/channels/', '.\\spec\\channels\\'
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/helper_example_group_spec.rb | spec/rspec/rails/example/helper_example_group_spec.rb | module RSpec::Rails
RSpec.describe HelperExampleGroup, :with_isolated_config do
module ::FoosHelper
class InternalClass
end
end
subject { HelperExampleGroup }
it_behaves_like "an rspec-rails example group mixin", :helper,
'./spec/helpers/', '.\\spec\\helpers\\'
it "provides a controller_path based on the helper module's name" do
example = double
allow(example).to receive_message_chain(:example_group, :described_class) { FoosHelper }
helper_spec = Object.new.extend HelperExampleGroup
expect(helper_spec.__send__(:_controller_path, example)).to eq("foos")
end
describe "#helper" do
it "returns the instance of AV::Base provided by AV::TC::Behavior" do
without_partial_double_verification do
helper_spec = Object.new.extend HelperExampleGroup
expect(helper_spec).to receive(:view_assigns)
av_tc_b_view = double('_view')
expect(av_tc_b_view).to receive(:assign)
allow(helper_spec).to receive(:_view) { av_tc_b_view }
expect(helper_spec.helper).to eq(av_tc_b_view)
end
end
before do
Object.const_set(:ApplicationHelper, Module.new)
end
after do
Object.__send__(:remove_const, :ApplicationHelper)
end
it "includes ApplicationHelper" do
group = RSpec::Core::ExampleGroup.describe do
include HelperExampleGroup
if ActionView::Base.respond_to?(:empty)
def _view
ActionView::Base.empty
end
else
def _view
ActionView::Base.new
end
end
end
expect(group.new.helper).to be_kind_of(ApplicationHelper)
end
end
end
RSpec.describe HelperExampleGroup::ClassMethods do
describe "determine_default_helper_class" do
let(:group) do
RSpec::Core::ExampleGroup.describe do
include HelperExampleGroup
end
end
context "the described is a module" do
it "returns the module" do
allow(group).to receive(:described_class) { FoosHelper }
expect(group.determine_default_helper_class("ignore this"))
.to eq(FoosHelper)
end
end
context "the described is a class" do
it "returns nil" do
allow(group).to receive(:described_class) { FoosHelper::InternalClass }
expect(group.determine_default_helper_class("ignore this"))
.to be_nil
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/rails_example_group_spec.rb | spec/rspec/rails/example/rails_example_group_spec.rb | module RSpec::Rails
RSpec.describe RailsExampleGroup, :with_isolated_config do
it 'supports tagged_logger' do
expect(described_class.private_instance_methods).to include(:tagged_logger)
end
it 'does not leak context between example groups' do
groups =
[
RSpec::Core::ExampleGroup.describe("A group") do
include RSpec::Rails::RailsExampleGroup
specify { expect(ActiveSupport::ExecutionContext.to_h).to eq({}) }
end,
RSpec::Core::ExampleGroup.describe("A controller group", type: :controller) do
specify do
Rails.error.set_context(foo: "bar")
expect(ActiveSupport::ExecutionContext.to_h).to eq(foo: "bar")
end
end,
RSpec::Core::ExampleGroup.describe("Another group") do
include RSpec::Rails::RailsExampleGroup
specify { expect(ActiveSupport::ExecutionContext.to_h).to eq({}) }
end
]
results =
groups.map do |group|
group.run(failure_reporter) ? true : failure_reporter.exceptions
end
expect(results).to all be true
end
it 'will not leak ActiveSupport::CurrentAttributes between examples' do
group =
RSpec::Core::ExampleGroup.describe("A group", order: :defined) do
include RSpec::Rails::RailsExampleGroup
# rubocop:disable Lint/ConstantDefinitionInBlock
class CurrentSample < ActiveSupport::CurrentAttributes
attribute :request_id
end
# rubocop:enable Lint/ConstantDefinitionInBlock
it 'sets a current attribute' do
CurrentSample.request_id = '123'
expect(CurrentSample.request_id).to eq('123')
end
it 'does not leak current attributes' do
expect(CurrentSample.request_id).to eq(nil)
end
end
expect(
group.run(failure_reporter) ? true : failure_reporter.exceptions
).to be true
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/routing_example_group_spec.rb | spec/rspec/rails/example/routing_example_group_spec.rb | module RSpec::Rails
RSpec.describe RoutingExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :routing,
'./spec/routing/', '.\\spec\\routing\\'
describe "named routes" do
it "delegates them to the route_set" do
group = RSpec::Core::ExampleGroup.describe do
include RoutingExampleGroup
end
example = group.new
# Yes, this is quite invasive
url_helpers = double('url_helpers', foo_path: "foo")
routes = double('routes', url_helpers: url_helpers)
allow(example).to receive_messages(routes: routes)
expect(example.foo_path).to eq("foo")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/job_example_group_spec.rb | spec/rspec/rails/example/job_example_group_spec.rb | module RSpec::Rails
RSpec.describe JobExampleGroup, :with_isolated_config do
if defined?(ActiveJob)
it_behaves_like "an rspec-rails example group mixin", :job,
'./spec/jobs/', '.\\spec\\jobs\\'
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/model_example_group_spec.rb | spec/rspec/rails/example/model_example_group_spec.rb | module RSpec::Rails
RSpec.describe ModelExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :model,
'./spec/models/', '.\\spec\\models\\'
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/mailbox_example_group_spec.rb | spec/rspec/rails/example/mailbox_example_group_spec.rb | require "rspec/rails/feature_check"
class ApplicationMailbox
class << self
attr_accessor :received
def receive(*)
self.received += 1
end
end
self.received = 0
end
module RSpec
module Rails
RSpec.describe MailboxExampleGroup, :with_isolated_config, skip: !RSpec::Rails::FeatureCheck.has_action_mailbox? do
it_behaves_like "an rspec-rails example group mixin", :mailbox,
'./spec/mailboxes/', '.\\spec\\mailboxes\\'
def group_for(klass)
RSpec::Core::ExampleGroup.describe klass do
include MailboxExampleGroup
end
end
let(:group) { group_for(::ApplicationMailbox) }
let(:example) { group.new }
describe '#have_been_delivered' do
it 'raises on undelivered mail' do
expect {
expect(double('IncomingEmail', delivered?: false)).to example.have_been_delivered
}.to raise_error(/have been delivered/)
end
it 'does not raise otherwise' do
expect(double('IncomingEmail', delivered?: true)).to example.have_been_delivered
end
end
describe '#have_bounced' do
it 'raises on unbounced mail' do
expect {
expect(double('IncomingEmail', bounced?: false)).to example.have_bounced
}.to raise_error(/have bounced/)
end
it 'does not raise otherwise' do
expect(double('IncomingEmail', bounced?: true)).to example.have_bounced
end
end
describe '#have_failed' do
it 'raises on unfailed mail' do
expect {
expect(double('IncomingEmail', failed?: false)).to example.have_failed
}.to raise_error(/have failed/)
end
it 'does not raise otherwise' do
expect(double('IncomingEmail', failed?: true)).to example.have_failed
end
end
describe '#process' do
before do
allow(RSpec::Rails::MailboxExampleGroup).to receive(:create_inbound_email) do |attributes|
mail = double('Mail::Message', attributes)
double('InboundEmail', mail: mail)
end
end
it 'sends mail to the mailbox' do
expect {
example.process(to: ['test@example.com'])
}.to change(::ApplicationMailbox, :received).by(1)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/request_example_group_spec.rb | spec/rspec/rails/example/request_example_group_spec.rb | module RSpec::Rails
RSpec.describe RequestExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :request,
'./spec/requests/', '.\\spec\\requests\\',
'./spec/integration/', '.\\spec\\integration\\',
'./spec/api/', '.\\spec\\api\\'
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/mailer_example_group_spec.rb | spec/rspec/rails/example/mailer_example_group_spec.rb | module RSpec::Rails
RSpec.describe MailerExampleGroup, :with_isolated_config do
module ::Rails; end
before do
allow(Rails).to receive_message_chain(:application, :routes, :url_helpers).and_return(Rails)
allow(Rails.application).to receive(:config).and_return(double("Rails.application.config").as_null_object)
allow(Rails).to receive_message_chain(:configuration, :action_mailer, :default_url_options).and_return({})
end
it_behaves_like "an rspec-rails example group mixin", :mailer,
'./spec/mailers/', '.\\spec\\mailers\\'
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/example/feature_example_group_spec.rb | spec/rspec/rails/example/feature_example_group_spec.rb | module RSpec::Rails
RSpec.describe FeatureExampleGroup, :with_isolated_config do
it_behaves_like "an rspec-rails example group mixin", :feature,
'./spec/features/', '.\\spec\\features\\'
it "includes Rails route helpers" do
with_isolated_stderr do
Rails.application.routes.draw do
get "/foo", as: :foo, to: "foo#bar"
end
end
group = RSpec::Core::ExampleGroup.describe do
include FeatureExampleGroup
end
expect(group.new.foo_path).to eq("/foo")
expect(group.new.foo_url).to eq("http://www.example.com/foo")
end
context "when nested inside a request example group" do
it "includes Rails route helpers" do
Rails.application.routes.draw do
get "/foo", as: :foo, to: "foo#bar"
end
outer_group = RSpec::Core::ExampleGroup.describe do
include RequestExampleGroup
end
group = outer_group.describe do
include FeatureExampleGroup
end
expect(group.new.foo_path).to eq("/foo")
expect(group.new.foo_url).to eq("http://www.example.com/foo")
end
end
describe "#visit" do
it "raises an error informing about missing Capybara" do
group = RSpec::Core::ExampleGroup.describe do
include FeatureExampleGroup
end
expect {
group.new.visit('/foobar')
}.to raise_error(/Capybara not loaded/)
end
it "is resistant to load order errors" do
capybara = Module.new do
def visit(url)
"success: #{url}"
end
end
group = RSpec::Core::ExampleGroup.describe do
include capybara
include FeatureExampleGroup
end
expect(group.new.visit("/foo")).to eq("success: /foo")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/action_mailbox_spec.rb | spec/rspec/rails/matchers/action_mailbox_spec.rb | require "rspec/rails/feature_check"
class ApplicationMailbox
class Router
def match_to_mailbox(*)
Inbox
end
end
def self.router
Router.new
end
end
class Inbox < ApplicationMailbox; end
class Otherbox < ApplicationMailbox; end
RSpec.describe "ActionMailbox matchers", skip: !RSpec::Rails::FeatureCheck.has_action_mailbox? do
describe "receive_inbound_email" do
let(:to) { ['to@example.com'] }
before do
allow(RSpec::Rails::MailboxExampleGroup).to receive(:create_inbound_email) do |attributes|
mail = double('Mail::Message', attributes)
double('InboundEmail', mail: mail)
end
end
it "passes when it receives inbound email" do
expect(Inbox).to receive_inbound_email(to: to)
end
it "passes when negated when it doesn't receive inbound email" do
expect(Otherbox).not_to receive_inbound_email(to: to)
end
it "fails when it doesn't receive inbound email" do
expect {
expect(Otherbox).to receive_inbound_email(to: to)
}.to raise_error(/expected mail to to@example.com to route to Otherbox, but routed to Inbox/)
end
it "fails when negated when it receives inbound email" do
expect {
expect(Inbox).not_to receive_inbound_email(to: to)
}.to raise_error(/expected mail to to@example.com not to route to Inbox/)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/relation_match_array_spec.rb | spec/rspec/rails/matchers/relation_match_array_spec.rb | RSpec.describe "ActiveSupport::Relation match_array matcher" do
before { MockableModel.delete_all }
let!(:models) { Array.new(3) { MockableModel.create } }
it "verifies that the scope returns the records on the right hand side, regardless of order" do
expect(MockableModel.all).to match_array(models.reverse)
end
it "fails if the scope encompasses more records than on the right hand side" do
MockableModel.create
expect(MockableModel.all).not_to match_array(models.reverse)
end
it "fails if the scope encompasses fewer records than on the right hand side" do
expect(MockableModel.limit(models.length - 1)).not_to match_array(models.reverse)
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/has_spec.rb | spec/rspec/rails/matchers/has_spec.rb | class CollectionOwner < ActiveRecord::Base
connection.execute <<-SQL
CREATE TABLE collection_owners (
id integer PRIMARY KEY AUTOINCREMENT
)
SQL
has_many :associated_items do
def has_some_quality?; true end
end
end
class AssociatedItem < ActiveRecord::Base
connection.execute <<-SQL
CREATE TABLE associated_items (
id integer PRIMARY KEY AUTOINCREMENT,
collection_owner_id integer
)
SQL
belongs_to :collection_owner
end
RSpec.describe "should have_xxx" do
it "works with ActiveRecord::Associations::CollectionProxy" do
owner = CollectionOwner.new
expect(owner.associated_items).to have_some_quality
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/route_to_spec.rb | spec/rspec/rails/matchers/route_to_spec.rb | RSpec.describe "route_to" do
include RSpec::Rails::Matchers::RoutingMatchers
include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers
def assert_recognizes(*)
# no-op
end
it "provides a description" do
matcher = route_to("these" => "options")
matcher.matches?(get: "path")
description =
if RUBY_VERSION >= '3.4'
"route {get: \"path\"} to {\"these\" => \"options\"}"
else
"route {:get=>\"path\"} to {\"these\"=>\"options\"}"
end
expect(matcher.description).to eq(description)
end
it "delegates to assert_recognizes" do
expect(self).to receive(:assert_recognizes).with({ "these" => "options" }, { method: :get, path: "path" }, {})
expect({ get: "path" }).to route_to("these" => "options")
end
context "with shortcut syntax" do
it "routes with extra options" do
expect(self).to receive(:assert_recognizes).with({ controller: "controller", action: "action", extra: "options" }, { method: :get, path: "path" }, {})
expect(get("path")).to route_to("controller#action", extra: "options")
end
it "routes without extra options" do
expect(self).to receive(:assert_recognizes).with(
{ controller: "controller", action: "action" },
{ method: :get, path: "path" },
{}
)
expect(get("path")).to route_to("controller#action")
end
it "routes with one query parameter" do
expect(self).to receive(:assert_recognizes).with(
{ controller: "controller", action: "action", queryitem: "queryvalue" },
{ method: :get, path: "path" },
{ 'queryitem' => 'queryvalue' }
)
expect(get("path?queryitem=queryvalue")).to route_to("controller#action", queryitem: 'queryvalue')
end
it "routes with multiple query parameters" do
expect(self).to receive(:assert_recognizes).with(
{ controller: "controller", action: "action", queryitem: "queryvalue", qi2: 'qv2' },
{ method: :get, path: "path" },
{ 'queryitem' => 'queryvalue', 'qi2' => 'qv2' }
)
expect(get("path?queryitem=queryvalue&qi2=qv2")).to route_to("controller#action", queryitem: 'queryvalue', qi2: 'qv2')
end
it "routes with nested query parameters" do
expect(self).to receive(:assert_recognizes).with(
{ :controller => "controller", :action => "action", 'queryitem' => { 'qi2' => 'qv2' } },
{ method: :get, path: "path" },
{ 'queryitem' => { 'qi2' => 'qv2' } }
)
expect(get("path?queryitem[qi2]=qv2")).to route_to("controller#action", 'queryitem' => { 'qi2' => 'qv2' })
end
end
context "with should" do
context "when assert_recognizes passes" do
it "passes" do
expect do
expect({ get: "path" }).to route_to("these" => "options")
end.to_not raise_exception
end
end
context "when assert_recognizes fails with an assertion failure" do
it "fails with message from assert_recognizes" do
def assert_recognizes(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
expect do
expect({ get: "path" }).to route_to("these" => "options")
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, "this message")
end
end
context "when assert_recognizes fails with a routing error" do
it "fails with message from assert_recognizes" do
def assert_recognizes(*)
raise ActionController::RoutingError, "this message"
end
expect do
expect({ get: "path" }).to route_to("these" => "options")
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, "this message")
end
end
context "when an exception is raised" do
it "raises that exception" do
def assert_recognizes(*)
raise "oops"
end
expect do
expect({ get: "path" }).to route_to("these" => "options")
end.to raise_exception("oops")
end
end
end
context "with should_not" do
context "when assert_recognizes passes" do
it "fails with custom message" do
message =
if RUBY_VERSION >= '3.4'
/expected \{get: "path"\} not to route to \{"these" => "options"\}/
else
/expected \{:get=>"path"\} not to route to \{"these"=>"options"\}/
end
expect {
expect({ get: "path" }).not_to route_to("these" => "options")
}.to raise_error(message)
end
end
context "when assert_recognizes fails with an assertion failure" do
it "passes" do
def assert_recognizes(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
expect do
expect({ get: "path" }).not_to route_to("these" => "options")
end.to_not raise_error
end
end
context "when assert_recognizes fails with a routing error" do
it "passes" do
def assert_recognizes(*)
raise ActionController::RoutingError, "this message"
end
expect do
expect({ get: "path" }).not_to route_to("these" => "options")
end.to_not raise_error
end
end
context "when an exception is raised" do
it "raises that exception" do
def assert_recognizes(*)
raise "oops"
end
expect do
expect({ get: "path" }).not_to route_to("these" => "options")
end.to raise_exception("oops")
end
end
end
it "uses failure message from assert_recognizes" do
def assert_recognizes(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
expect do
expect({ "this" => "path" }).to route_to("these" => "options")
end.to raise_error("this message")
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/be_new_record_spec.rb | spec/rspec/rails/matchers/be_new_record_spec.rb | RSpec.describe "be_new_record" do
context "a new record" do
let(:record) { double('record', new_record?: true) }
it "passes" do
expect(record).to be_new_record
end
it "fails with custom failure message" do
expect {
expect(record).not_to be_new_record
}.to raise_exception(/expected .* to be persisted, but was a new record/)
end
end
context "a persisted record" do
let(:record) { double('record', new_record?: false) }
it "fails" do
expect(record).not_to be_new_record
end
it "fails with custom failure message" do
expect {
expect(record).to be_new_record
}.to raise_exception(/expected .* to be a new record, but was persisted/)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/have_enqueued_mail_spec.rb | spec/rspec/rails/matchers/have_enqueued_mail_spec.rb | require "rspec/rails/feature_check"
if RSpec::Rails::FeatureCheck.has_active_job?
require "action_mailer"
require "rspec/rails/matchers/have_enqueued_mail"
class GlobalIDArgument
include GlobalID::Identification
def id; 1; end
def to_global_id(options = {}); super(options.merge(app: 'rspec-rails')); end
end
class TestMailer < ActionMailer::Base
def test_email; end
def email_with_args(arg1, arg2); end
def email_with_optional_args(required_arg, optional_arg = nil); end
end
class AnotherTestMailer < ActionMailer::Base
def test_email; end
end
class NonMailerJob < ActiveJob::Base
def perform; end
end
if RSpec::Rails::FeatureCheck.has_action_mailer_unified_delivery?
class UnifiedMailer < ActionMailer::Base
self.delivery_job = ActionMailer::MailDeliveryJob
def test_email; end
def email_with_args(arg1, arg2); end
end
if RSpec::Rails::FeatureCheck.has_action_mailer_legacy_delivery_job?
class DeliveryJobSubClass < ActionMailer::DeliveryJob
end
else
class DeliveryJobSubClass < ActionMailer::MailDeliveryJob
end
end
class UnifiedMailerWithDeliveryJobSubClass < ActionMailer::Base
self.delivery_job = DeliveryJobSubClass
def test_email; end
end
end
end
RSpec.describe "HaveEnqueuedMail matchers", skip: !RSpec::Rails::FeatureCheck.has_active_job? do
before do
ActiveJob::Base.queue_adapter = :test
end
around do |example|
original_logger = ActiveJob::Base.logger
ActiveJob::Base.logger = Logger.new(nil) # Silence messages "[ActiveJob] Enqueued ...".
example.run
ActiveJob::Base.logger = original_logger
end
around do |example|
original_value = RSpec::Mocks.configuration.verify_partial_doubles?
example.run
ensure
RSpec::Mocks.configuration.verify_partial_doubles = original_value
end
describe "have_enqueued_mail" do
it "passes when a mailer method is called with deliver_later" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email)
end
it "passes when using the have_enqueued_email alias" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_email(TestMailer, :test_email)
end
it "passes when using the enqueue_mail alias" do
expect {
TestMailer.test_email.deliver_later
}.to enqueue_mail(TestMailer, :test_email)
end
it "passes when using the enqueue_email alias" do
expect {
TestMailer.test_email.deliver_later
}.to enqueue_email(TestMailer, :test_email)
end
it "passes when negated" do
expect { }.not_to have_enqueued_mail(TestMailer, :test_email)
end
it "passes when given 0 arguments" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_email
end
it "passes when negated with 0 arguments" do
expect { }.not_to have_enqueued_email
end
it "passes when negated with 0 arguments and a non-mailer job is enqueued" do
expect { NonMailerJob.perform_later }.not_to have_enqueued_email
end
it "passes when only given mailer argument" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_email(TestMailer)
end
it "passes when negated with only mailer arguments" do
expect { }.not_to have_enqueued_email(TestMailer)
end
it "ensure that the right mailer is enqueued" do
expect {
expect {
AnotherTestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer)
}.to fail_with(/expected to enqueue TestMailer exactly 1 time but enqueued 0/)
end
it "counts only emails enqueued in the block" do
TestMailer.test_email.deliver_later
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).once
end
it "fails when too many emails are enqueued" do
expect {
expect {
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).exactly(1)
}.to fail_with(/expected to enqueue TestMailer.test_email exactly 1 time/)
end
it "matches based on mailer class and method name" do
expect {
TestMailer.test_email.deliver_later
TestMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).once
end
it "passes with multiple emails" do
expect {
TestMailer.test_email.deliver_later
TestMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).and have_enqueued_mail(TestMailer, :email_with_args)
end
it 'fails when negated and mail is enqueued' do
expect {
expect {
TestMailer.test_email.deliver_later
}.not_to have_enqueued_mail(TestMailer, :test_email)
}.to fail_with(/expected not to enqueue TestMailer.test_email at least 1 time but enqueued 1/)
end
it "passes with :once count" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).once
end
it "passes with :twice count" do
expect {
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).twice
end
it "passes with :thrice count" do
expect {
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).thrice
end
it "passes with at_least when enqueued emails are over the limit" do
expect {
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).at_least(:once)
end
it "passes with at_most when enqueued emails are under the limit" do
expect {
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).at_most(:twice)
end
it "generates a failure message when given 0 argument" do
expect {
expect { }.to have_enqueued_mail.at_least(:once)
}.to fail_with(/expected to enqueue ActionMailer::Base at least 1 time but enqueued 0/)
end
it "generates a failure message when given only mailer argument" do
expect {
expect { }.to have_enqueued_mail(TestMailer).at_least(:once)
}.to fail_with(/expected to enqueue TestMailer at least 1 time but enqueued 0/)
end
it "generates a failure message with at least hint" do
expect {
expect { }.to have_enqueued_mail(TestMailer, :test_email).at_least(:once)
}.to fail_with(/expected to enqueue TestMailer.test_email at least 1 time but enqueued 0/)
end
it "generates a failure message with at most hint" do
expect {
expect {
TestMailer.test_email.deliver_later
TestMailer.test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).at_most(:once)
}.to fail_with(/expected to enqueue TestMailer.test_email at most 1 time but enqueued 2/)
end
it "passes for mailer methods that accept arguments when the provided argument matcher is not used" do
expect {
TestMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args)
end
it "passes for mailer methods with default arguments" do
expect {
TestMailer.email_with_optional_args('required').deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_optional_args)
expect {
TestMailer.email_with_optional_args('required').deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_optional_args).with('required')
expect {
TestMailer.email_with_optional_args('required', 'optional').deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_optional_args).with('required', 'optional')
end
it "passes with provided argument matchers" do
expect {
TestMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with(1, 2)
expect {
TestMailer.email_with_args(1, 2).deliver_later
}.not_to have_enqueued_mail(TestMailer, :email_with_args).with(3, 4)
end
describe "verifying the arguments passed match the mailer's signature" do
it "fails if there is a mismatch" do
expect {
expect {
TestMailer.email_with_args(1).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with(1)
}.to fail_with(/Incorrect arguments passed to TestMailer: Wrong number of arguments/)
end
context "with partial double verification disabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = false
end
it "skips signature checks" do
expect { TestMailer.email_with_args(1).deliver_later }
.to have_enqueued_mail(TestMailer, :email_with_args).with(1)
end
end
context "when partial double verification is temporarily suspended" do
it "skips signature checks" do
without_partial_double_verification {
expect {
TestMailer.email_with_args(1).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with(1)
}
end
end
end
it "generates a failure message" do
expect {
expect { }.to have_enqueued_email(TestMailer, :test_email)
}.to fail_with(/expected to enqueue TestMailer.test_email/)
end
it "generates a failure message with arguments" do
expect {
expect { }.to have_enqueued_email(TestMailer, :email_with_args).with(1, 2)
}.to fail_with(/expected to enqueue TestMailer.email_with_args exactly 1 time with \[1, 2\], but enqueued 0/)
end
it "passes when deliver_later is called with a wait_until argument" do
send_time = Date.tomorrow.noon
expect {
TestMailer.test_email.deliver_later(wait_until: send_time)
}.to have_enqueued_email(TestMailer, :test_email).at(send_time)
end
it "generates a failure message with at" do
send_time = Date.tomorrow.noon
expect {
expect {
TestMailer.test_email.deliver_later(wait_until: send_time + 1)
}.to have_enqueued_email(TestMailer, :test_email).at(send_time)
}.to fail_with(/expected to enqueue TestMailer.test_email exactly 1 time at #{send_time.strftime('%F %T')}/)
end
it "accepts composable matchers as an at date" do
future = 1.minute.from_now
slightly_earlier = 58.seconds.from_now
expect {
TestMailer.test_email.deliver_later(wait_until: slightly_earlier)
}.to have_enqueued_email(TestMailer, :test_email).at(a_value_within(5.seconds).of(future))
end
it "passes when deliver_later is called with a queue argument" do
expect {
TestMailer.test_email.deliver_later(queue: 'urgent_mail')
}.to have_enqueued_email(TestMailer, :test_email).on_queue('urgent_mail')
end
it "generates a failure message with on_queue" do
expect {
expect {
TestMailer.test_email.deliver_later(queue: 'not_urgent_mail')
}.to have_enqueued_email(TestMailer, :test_email).on_queue('urgent_mail')
}.to fail_with(/expected to enqueue TestMailer.test_email exactly 1 time on queue urgent_mail/)
end
it "generates a failure message with unmatching enqueued mail jobs" do
send_time = Date.tomorrow.noon
queue = 'urgent_mail'
message = "expected to enqueue TestMailer.email_with_args exactly 1 time with [1, 2], but enqueued 0" \
"\nQueued deliveries:" \
"\n TestMailer.test_email" \
"\n TestMailer.email_with_args with [3, 4], on queue #{queue}, at #{send_time}"
expect {
expect {
NonMailerJob.perform_later
TestMailer.test_email.deliver_later
TestMailer.email_with_args(3, 4).deliver_later(wait_until: send_time, queue: queue)
}.to have_enqueued_email(TestMailer, :email_with_args).with(1, 2)
}.to fail_with(message)
end
it "throws descriptive error when no test adapter set" do
queue_adapter = ActiveJob::Base.queue_adapter
ActiveJob::Base.queue_adapter = :inline
expect {
expect { TestMailer.test_email.deliver_later }.to have_enqueued_mail(TestMailer, :test_email)
}.to raise_error("To use HaveEnqueuedMail matcher set `ActiveJob::Base.queue_adapter = :test`")
ActiveJob::Base.queue_adapter = queue_adapter
end
it "fails with with block with incorrect data" do
expect {
expect {
TestMailer.email_with_args('asdf', 'zxcv').deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with { |first_arg, _second_arg|
expect(first_arg).to eq("zxcv")
}
}.to raise_error { |e|
expect(e.message).to match(/expected: "zxcv"/)
expect(e.message).to match(/got: "asdf"/)
}
end
it "passes multiple arguments to with block" do
expect {
TestMailer.email_with_args('asdf', 'zxcv').deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with { |first_arg, second_arg|
expect(first_arg).to eq("asdf")
expect(second_arg).to eq("zxcv")
}
end
it "only calls with block if other conditions are met" do
noon = Date.tomorrow.noon
midnight = Date.tomorrow.midnight
expect {
TestMailer.email_with_args('high', 'noon').deliver_later(wait_until: noon)
TestMailer.email_with_args('midnight', 'rider').deliver_later(wait_until: midnight)
}.to have_enqueued_mail(TestMailer, :email_with_args).at(noon).with { |first_arg, second_arg|
expect(first_arg).to eq('high')
expect(second_arg).to eq('noon')
}
end
context 'when parameterized' do
before do
unless RSpec::Rails::FeatureCheck.has_action_mailer_parameterized?
skip "This version of Rails does not support parameterized mailers"
end
end
it "passes when mailer is parameterized" do
expect {
TestMailer.with('foo' => 'bar').test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email)
end
it "passes when mixing parameterized and non-parameterized emails" do
expect {
TestMailer.with('foo' => 'bar').test_email.deliver_later
TestMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).and have_enqueued_mail(TestMailer, :email_with_args)
end
it "passes with provided argument matchers" do
expect {
TestMailer.with('foo' => 'bar').test_email.deliver_later
}.to have_enqueued_mail(TestMailer, :test_email).with('foo' => 'bar')
expect {
TestMailer.with('foo' => 'bar').email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with({ 'foo' => 'bar' }, 1, 2)
end
it "fails if the arguments do not match the mailer method's signature" do
expect {
expect {
TestMailer.with('foo' => 'bar').email_with_args(1).deliver_later
}.to have_enqueued_mail(TestMailer, :email_with_args).with({ 'foo' => 'bar' }, 1)
}.to raise_error(/Incorrect arguments passed to TestMailer: Wrong number of arguments/)
end
end
context 'mailer job is unified', skip: !RSpec::Rails::FeatureCheck.has_action_mailer_unified_delivery? do
it "passes when mailer is parameterized" do
expect {
UnifiedMailer.with('foo' => 'bar').test_email.deliver_later
}.to have_enqueued_mail(UnifiedMailer, :test_email)
end
it "passes when mixing parameterized and non-parameterized emails" do
expect {
UnifiedMailer.with('foo' => 'bar').test_email.deliver_later
UnifiedMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(UnifiedMailer, :test_email).and have_enqueued_mail(UnifiedMailer, :email_with_args)
end
it "matches arguments when mailer has only args" do
expect {
UnifiedMailer.email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(UnifiedMailer, :email_with_args).with(1, 2)
end
it "passes with provided argument matchers" do
expect {
UnifiedMailer.with('foo' => 'bar').test_email.deliver_later
}.to have_enqueued_mail(UnifiedMailer, :test_email).with(
a_hash_including(params: { 'foo' => 'bar' })
)
expect {
UnifiedMailer.with('foo' => 'bar').email_with_args(1, 2).deliver_later
}.to have_enqueued_mail(UnifiedMailer, :email_with_args).with(
a_hash_including(params: { 'foo' => 'bar' }, args: [1, 2])
)
end
it "passes when given a global id serialized argument" do
expect {
UnifiedMailer.with(inquiry: GlobalIDArgument.new).test_email.deliver_later
}.to have_enqueued_email(UnifiedMailer, :test_email)
end
it "passes when using a mailer with `delivery_job` set to a sub class of `ActionMailer::DeliveryJob`" do
expect {
UnifiedMailerWithDeliveryJobSubClass.test_email.deliver_later
}.to have_enqueued_mail(UnifiedMailerWithDeliveryJobSubClass, :test_email)
end
it "fails if the arguments do not match the mailer method's signature" do
expect {
expect {
UnifiedMailer.with('foo' => 'bar').email_with_args(1).deliver_later
}.to have_enqueued_mail(UnifiedMailer, :email_with_args).with(
a_hash_including(params: { 'foo' => 'bar' }, args: [1])
)
}.to fail_with(/Incorrect arguments passed to UnifiedMailer: Wrong number of arguments/)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/be_routable_spec.rb | spec/rspec/rails/matchers/be_routable_spec.rb | RSpec.describe "be_routable" do
include RSpec::Rails::Matchers::RoutingMatchers
attr_reader :routes
before { @routes = double("routes") }
it "provides a description" do
expect(be_routable.description).to eq("be routable")
end
context "with should" do
it "passes if routes recognize the path" do
allow(routes).to receive(:recognize_path) { {} }
expect do
expect({ get: "/a/path" }).to be_routable
end.to_not raise_error
end
it "fails if routes do not recognize the path" do
allow(routes).to receive(:recognize_path) { raise ActionController::RoutingError, 'ignore' }
message =
if RUBY_VERSION >= '3.4'
/expected \{get: "\/a\/path"\} to be routable/
else
/expected \{:get=>"\/a\/path"\} to be routable/
end
expect do
expect({ get: "/a/path" }).to be_routable
end.to raise_error(message)
end
end
context "with should_not" do
it "passes if routes do not recognize the path" do
allow(routes).to receive(:recognize_path) { raise ActionController::RoutingError, 'ignore' }
expect do
expect({ get: "/a/path" }).not_to be_routable
end.to_not raise_error
end
it "fails if routes recognize the path" do
allow(routes).to receive(:recognize_path) { { controller: "foo" } }
message =
if RUBY_VERSION >= '3.4'
/expected \{get: "\/a\/path"\} not to be routable, but it routes to \{controller: "foo"\}/
else
/expected \{:get=>"\/a\/path"\} not to be routable, but it routes to \{:controller=>"foo"\}/
end
expect do
expect({ get: "/a/path" }).not_to be_routable
end.to raise_error(message)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/send_email_spec.rb | spec/rspec/rails/matchers/send_email_spec.rb | RSpec.describe "send_email" do
let(:mailer) do
Class.new(ActionMailer::Base) do
self.delivery_method = :test
def test_email
mail(
from: "from@example.com",
cc: "cc@example.com",
bcc: "bcc@example.com",
to: "to@example.com",
subject: "Test email",
body: "Test email body"
)
end
end
end
it "checks email sending by all params together" do
expect {
mailer.test_email.deliver_now
}.to send_email(
from: "from@example.com",
to: "to@example.com",
cc: "cc@example.com",
bcc: "bcc@example.com",
subject: "Test email",
body: a_string_including("Test email body")
)
end
it "checks email sending by no params" do
expect {
mailer.test_email.deliver_now
}.to send_email
end
it "with to_not" do
expect {
mailer.test_email.deliver_now
}.to_not send_email(
from: "failed@example.com"
)
end
it "fails with a clear message" do
expect {
expect { mailer.test_email.deliver_now }.to send_email(from: 'failed@example.com')
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, <<~MSG.strip)
No matching emails were sent.
The following emails were sent:
- subject: Test email, from: ["from@example.com"], to: ["to@example.com"], cc: ["cc@example.com"], bcc: ["bcc@example.com"]
MSG
end
it "fails with a clear message when no emails were sent" do
expect {
expect { }.to send_email
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, <<~MSG.strip)
No matching emails were sent.
There were no any emails sent inside the expectation block.
MSG
end
it "fails with a clear message for negated version" do
expect {
expect { mailer.test_email.deliver_now }.to_not send_email(from: "from@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, "Expected not to send an email but it was sent.")
end
it "fails for multiple matches" do
expect {
expect { 2.times { mailer.test_email.deliver_now } }.to send_email(from: "from@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, <<~MSG.strip)
More than 1 matching emails were sent.
The following emails were sent:
- subject: Test email, from: ["from@example.com"], to: ["to@example.com"], cc: ["cc@example.com"], bcc: ["bcc@example.com"]
- subject: Test email, from: ["from@example.com"], to: ["to@example.com"], cc: ["cc@example.com"], bcc: ["bcc@example.com"]
MSG
end
context "with compound matching" do
it "works when both matchings pass" do
expect {
expect {
mailer.test_email.deliver_now
}.to send_email(to: "to@example.com").and send_email(from: "from@example.com")
}.to_not raise_error
end
it "works when first matching fails" do
expect {
expect {
mailer.test_email.deliver_now
}.to send_email(to: "no@example.com").and send_email(to: "to@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, <<~MSG.strip)
No matching emails were sent.
The following emails were sent:
- subject: Test email, from: ["from@example.com"], to: ["to@example.com"], cc: ["cc@example.com"], bcc: ["bcc@example.com"]
MSG
end
it "works when second matching fails" do
expect {
expect {
mailer.test_email.deliver_now
}.to send_email(to: "to@example.com").and send_email(to: "no@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, <<~MSG.strip)
No matching emails were sent.
The following emails were sent:
- subject: Test email, from: ["from@example.com"], to: ["to@example.com"], cc: ["cc@example.com"], bcc: ["bcc@example.com"]
MSG
end
end
context "with a custom negated version defined" do
define_negated_matcher :not_send_email, :send_email
it "works with a negated version" do
expect {
mailer.test_email.deliver_now
}.to not_send_email(
from: "failed@example.com"
)
end
it "fails with a clear message" do
expect {
expect { mailer.test_email.deliver_now }.to not_send_email(from: "from@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, "Expected not to send an email but it was sent.")
end
context "with a compound negated version" do
it "works when both matchings pass" do
expect {
expect {
mailer.test_email.deliver_now
}.to not_send_email(to: "noto@example.com").and not_send_email(from: "nofrom@example.com")
}.to_not raise_error
end
it "works when first matching fails" do
expect {
expect {
mailer.test_email.deliver_now
}.to not_send_email(to: "to@example.com").and send_email(to: "to@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, a_string_including(<<~MSG.strip))
Expected not to send an email but it was sent.
MSG
end
it "works when second matching fails" do
expect {
expect {
mailer.test_email.deliver_now
}.to send_email(to: "to@example.com").and not_send_email(to: "to@example.com")
}.to raise_error(RSpec::Expectations::ExpectationNotMetError, a_string_including(<<~MSG.strip))
Expected not to send an email but it was sent.
MSG
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/be_valid_spec.rb | spec/rspec/rails/matchers/be_valid_spec.rb | require 'rspec/rails/matchers/be_valid'
RSpec.describe "be_valid matcher" do
class Post
include ActiveModel::Validations
attr_accessor :title
validates_presence_of :title
end
class Book
def valid?
false
end
def errors
['the spine is broken', 'the pages are dog-eared']
end
end
class Boat
def valid?
false
end
end
class Car
def valid?
false
end
def errors(_)
end
end
let(:post) { Post.new }
let(:book) { Book.new }
let(:boat) { Boat.new }
let(:car) { Car.new }
it "includes the error messages in the failure message" do
expect {
expect(post).to be_valid
}.to raise_exception(/Title can.t be blank/)
end
it "includes the error messages for simple implementations of error messages" do
expect {
expect(book).to be_valid
}.to raise_exception(/the spine is broken/)
end
it "includes a brief error message for the simplest implementation of validity" do
expect {
expect(boat).to be_valid
}.to raise_exception(/expected .+ to be valid\z/)
end
it "includes a brief error message when error message is wrong arity" do
expect {
expect(car).to be_valid
}.to raise_exception(/expected .+ to be valid\z/)
end
it "includes a failure message for the negative case" do
allow(post).to receive(:valid?) { true }
expect {
expect(post).not_to be_valid
}.to raise_exception(/expected .* not to be valid/)
end
it "uses a custom failure message if provided" do
expect {
expect(post).to be_valid, "Post was not valid!"
}.to raise_exception(/Post was not valid!/)
end
it "includes the validation context if provided" do
expect(post).to receive(:valid?).with(:create) { true }
expect(post).to be_valid(:create)
end
it "does not include the validation context if not provided" do
expect(post).to receive(:valid?).with(no_args) { true }
expect(post).to be_valid
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/have_http_status_spec.rb | spec/rspec/rails/matchers/have_http_status_spec.rb | RSpec.describe "have_http_status" do
def create_response(opts = {})
ActionDispatch::TestResponse.new(opts.fetch(:status)).tap { |x|
x.request = ActionDispatch::Request.new({})
}
end
shared_examples_for "supports different response instances" do
context "given an ActionDispatch::Response" do
it "returns true for a response with the same code" do
response = ::ActionDispatch::Response.new(code).tap { |x|
x.request = ActionDispatch::Request.new({})
}
expect(matcher.matches?(response)).to be(true)
end
end
context "given a Rack::MockResponse" do
it "returns true for a response with the same code" do
response = ::Rack::MockResponse.new(code, {}, "")
expect(matcher.matches?(response)).to be(true)
end
end
context "given an ActionDispatch::TestResponse" do
it "returns true for a response with the same code" do
response = ::ActionDispatch::TestResponse.new(code).tap { |x|
x.request = ActionDispatch::Request.new({})
}
expect(matcher.matches?(response)).to be(true)
end
end
context "given something that acts as a Capybara::Session" do
it "returns true for a response with the same code" do
response = instance_double(
'::Capybara::Session',
status_code: code,
response_headers: {},
body: ""
)
expect(matcher.matches?(response)).to be(true)
end
end
it "returns false given another type" do
response = Object.new
expect(matcher.matches?(response)).to be(false)
end
it "has a failure message reporting it was given another type" do
response = Object.new
expect { matcher.matches?(response) }
.to change(matcher, :failure_message)
.to("expected a response object, but an instance of Object was received")
end
it "has a negated failure message reporting it was given another type" do
response = Object.new
expect { matcher.matches?(response) }
.to change(matcher, :failure_message_when_negated)
.to("expected a response object, but an instance of Object was received")
end
end
context "with a numeric status code" do
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(code) }
let(:code) { 209 }
end
describe "matching a response" do
it "returns true for a response with the same code" do
any_numeric_code = 209
have_numeric_code = have_http_status(any_numeric_code)
response = create_response(status: any_numeric_code)
expect(have_numeric_code.matches?(response)).to be(true)
end
it "returns false for a response with a different code" do
any_numeric_code = 209
have_numeric_code = have_http_status(any_numeric_code)
response = create_response(status: any_numeric_code + 1)
expect(have_numeric_code.matches?(response)).to be(false)
end
end
it "describes responding with the numeric status code" do
any_numeric_code = 209
have_numeric_code = have_http_status(any_numeric_code)
expect(have_numeric_code.description)
.to eq("respond with numeric status code 209")
end
it "has a failure message reporting the expected and actual status codes" do
any_numeric_code = 209
have_numeric_code = have_http_status(any_numeric_code)
response = create_response(status: any_numeric_code + 1)
expect { have_numeric_code.matches? response }
.to change(have_numeric_code, :failure_message)
.to("expected the response to have status code 209 but it was 210")
end
it "has a negated failure message reporting the expected status code" do
any_numeric_code = 209
have_numeric_code = have_http_status(any_numeric_code)
expect(have_numeric_code.failure_message_when_negated)
.to eq("expected the response not to have status code 209 but it did")
end
end
context "with a symbolic status" do
# :created => 201 status code
# see https://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option
let(:created_code) { 201 }
let(:created_symbolic_status) { :created }
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(created_symbolic_status) }
let(:code) { created_code }
end
describe "matching a response" do
it "returns true for a response with the equivalent code" do
any_symbolic_status = created_symbolic_status
have_symbolic_status = have_http_status(any_symbolic_status)
response = create_response(status: created_code)
expect(have_symbolic_status.matches?(response)).to be(true)
end
it "returns false for a response with a different code" do
any_symbolic_status = created_symbolic_status
have_symbolic_status = have_http_status(any_symbolic_status)
response = create_response(status: created_code + 1)
expect(have_symbolic_status.matches?(response)).to be(false)
end
end
it "describes responding by the symbolic and associated numeric status code" do
any_symbolic_status = created_symbolic_status
have_symbolic_status = have_http_status(any_symbolic_status)
expect(have_symbolic_status.description)
.to eq("respond with status code :created (201)")
end
it "has a failure message reporting the expected and actual statuses" do
any_symbolic_status = created_symbolic_status
have_symbolic_status = have_http_status(any_symbolic_status)
response = create_response(status: created_code + 1)
expect { have_symbolic_status.matches? response }
.to change(have_symbolic_status, :failure_message)
.to("expected the response to have status code :created (201) but it was :accepted (202)")
end
it "has a negated failure message reporting the expected status code" do
any_symbolic_status = created_symbolic_status
have_symbolic_status = have_http_status(any_symbolic_status)
expect(have_symbolic_status.failure_message_when_negated)
.to eq("expected the response not to have status code :created (201) but it did")
end
it "raises an ArgumentError" do
expect { have_http_status(:not_a_status) }.to raise_error ArgumentError
end
end
shared_examples_for 'status code matcher' do
# within the calling block, define:
# let(:expected_code) { <value> } # such as 555, 444, 333, 222
# let(:other_code) { <value> } # such as 555, 444, 333, 222
# let(:failure_message) {
# /an error status code \(5xx\) but it was 400/
# } # for example
# let(:negated_message) {
# /not to have an error status code \(5xx\) but it was 555/
# } # for example
# let(:description) {
# 'respond with an error status code (5xx)'
# } # for example
# subject(:matcher) { <matcher> } # e.g. { have_http_status(:error) }
describe "matching a response" do
it "returns true for a response with code" do
response = create_response(status: expected_code)
expect(matcher.matches?(response)).to be(true)
end
it "returns false for a response with a different code" do
response = create_response(status: other_code)
expect(matcher.matches?(response)).to be(false)
end
end
it "describes #{description}" do
expect(matcher.description).to eq(description)
end
it "has a failure message reporting the expected and actual status codes" do
response = create_response(status: other_code)
expect { matcher.matches? response }
.to change(matcher, :failure_message)
.to(failure_message)
end
it "has a negated failure message reporting the expected and actual status codes" do
response = create_response(status: expected_code)
expect { matcher.matches? response }
.to change(matcher, :failure_message_when_negated)
.to(negated_message)
end
end
context "with general status code group", ":error" do
# The error query is an alias for `server_error?`:
#
# - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L27
# - https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb
#
# `server_error?` is part of the Rack Helpers and is defined as:
#
# status >= 500 && status < 600
#
# See:
#
# - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L122
# - https://github.com/rack/rack/blob/master/lib/rack/response.rb
subject(:matcher) { have_http_status(:error) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 555 }
let(:other_code) { 400 }
let(:failure_message) { /an error status code \(5xx\) but it was 400/ }
let(:negated_message) {
/not to have an error status code \(5xx\) but it was 555/
}
let(:description) {
'respond with an error status code (5xx)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 555 }
end
end
context "with general status code group", ":server_error" do
subject(:matcher) { have_http_status(:server_error) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 555 }
let(:other_code) { 400 }
let(:failure_message) { /a server_error status code \(5xx\) but it was 400/ }
let(:negated_message) {
/not to have a server_error status code \(5xx\) but it was 555/
}
let(:description) {
'respond with a server_error status code (5xx)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 555 }
end
end
context "with general status code group", ":success" do
# The success query is an alias for `successful?`:
#
# - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L18
# - https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb
#
# `successful?` is part of the Rack Helpers and is defined as:
#
# status >= 200 && status < 300
#
# See:
#
# - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119
# - https://github.com/rack/rack/blob/master/lib/rack/response.rb
subject(:matcher) { have_http_status(:success) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 222 }
let(:other_code) { 400 }
let(:failure_message) {
/a success status code \(2xx\) but it was 400/
}
let(:negated_message) {
/not to have a success status code \(2xx\) but it was 222/
}
let(:description) {
'respond with a success status code (2xx)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 222 }
end
end
context "with general status code group", ":successful" do
subject(:matcher) { have_http_status(:successful) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 222 }
let(:other_code) { 400 }
let(:failure_message) {
/a successful status code \(2xx\) but it was 400/
}
let(:negated_message) {
/not to have a successful status code \(2xx\) but it was 222/
}
let(:description) {
'respond with a successful status code (2xx)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 222 }
end
end
context "with general status code group", ":missing" do
# The missing query is an alias for `not_found?`:
#
# - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L21
# - https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb
#
# `not_found?` is part of the Rack Helpers and is defined as:
#
# status == 404
#
# See:
#
# - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L130
# - https://github.com/rack/rack/blob/master/lib/rack/response.rb
subject(:matcher) { have_http_status(:missing) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 404 }
let(:other_code) { 400 }
let(:failure_message) {
/a missing status code \(404\) but it was 400/
}
let(:negated_message) {
/not to have a missing status code \(404\) but it was 404/
}
let(:description) {
'respond with a missing status code (404)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 404 }
end
end
context "with general status code group", ":not_found" do
subject(:matcher) { have_http_status(:not_found) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 404 }
let(:other_code) { 400 }
let(:failure_message) {
/a not_found status code \(404\) but it was 400/
}
let(:negated_message) {
/not to have a not_found status code \(404\) but it was 404/
}
let(:description) {
'respond with a not_found status code (404)'
}
end
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(:not_found) }
let(:code) { 404 }
end
end
context "with general status code group", ":redirect" do
# The redirect query is an alias for `redirection?`:
#
# - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L24
# - https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb
#
# `redirection?` is part of the Rack Helpers and is defined as:
#
# status >= 300 && status < 400
#
# See:
#
# - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L120
# - https://github.com/rack/rack/blob/master/lib/rack/response.rb
subject(:matcher) { have_http_status(:redirect) }
it_behaves_like 'status code matcher' do
let(:expected_code) { 308 }
let(:other_code) { 400 }
let(:failure_message) {
/a redirect status code \(3xx\) but it was 400/
}
let(:negated_message) {
/not to have a redirect status code \(3xx\) but it was 308/
}
let(:description) {
'respond with a redirect status code (3xx)'
}
end
it_behaves_like "supports different response instances" do
let(:code) { 308 }
end
end
context "with a nil status" do
it "raises an ArgumentError" do
expect { have_http_status(nil) }.to raise_error ArgumentError
end
end
shared_examples_for "does not use deprecated methods for Rails 5.2+" do
it "does not use deprecated method for Rails >= 5.2" do
previous_stderr = $stderr
begin
splitter = RSpec::Support::StdErrSplitter.new(previous_stderr)
$stderr = splitter
response = ::ActionDispatch::Response.new(code).tap { |x|
x.request = ActionDispatch::Request.new({})
}
expect(matcher.matches?(response)).to be(true)
expect(splitter.has_output?).to be false
ensure
$stderr = previous_stderr
end
end
end
context 'http status :missing' do
it_behaves_like "does not use deprecated methods for Rails 5.2+" do
subject(:matcher) { have_http_status(:missing) }
let(:code) { 404 }
end
end
context 'http status :success' do
it_behaves_like "does not use deprecated methods for Rails 5.2+" do
subject(:matcher) { have_http_status(:success) }
let(:code) { 222 }
end
end
context 'http status :error' do
it_behaves_like "does not use deprecated methods for Rails 5.2+" do
subject(:matcher) { have_http_status(:error) }
let(:code) { 555 }
end
end
context 'http status :not_found' do
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(:not_found) }
let(:code) { 404 }
end
end
context 'http status :successful' do
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(:successful) }
let(:code) { 222 }
end
end
context 'http status :server_error' do
it_behaves_like "supports different response instances" do
subject(:matcher) { have_http_status(:server_error) }
let(:code) { 555 }
end
end
context 'with deprecated rack status codes' do
it 'supports the original names' do
allow(Rack::Utils).to receive(:warn).with(/unprocessable_entity is deprecated/, anything)
expect(create_response(status: 422)).to have_http_status(:unprocessable_entity)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/be_a_new_spec.rb | spec/rspec/rails/matchers/be_a_new_spec.rb | RSpec.describe "be_a_new matcher" do
context "new record" do
let(:record) do
Class.new do
def new_record?; true; end
end.new
end
context "right class" do
it "passes" do
expect(record).to be_a_new(record.class)
end
end
context "wrong class" do
it "fails" do
expect(record).not_to be_a_new(String)
end
end
end
context "existing record" do
let(:record) do
Class.new do
def new_record?; false; end
end.new
end
context "right class" do
it "fails" do
expect(record).not_to be_a_new(record.class)
end
end
context "wrong class" do
it "fails" do
expect(record).not_to be_a_new(String)
end
end
end
describe "#with" do
context "right class and new record" do
let(:record) do
Class.new do
def initialize(attributes)
@attributes = attributes
end
def attributes
@attributes.stringify_keys
end
def new_record?; true; end
end.new(foo: 'foo', bar: 'bar')
end
context "all attributes same" do
it "passes" do
expect(record).to be_a_new(record.class).with(foo: 'foo', bar: 'bar')
end
end
context "one attribute same" do
it "passes" do
expect(record).to be_a_new(record.class).with(foo: 'foo')
end
end
context "with composable matchers" do
context "one attribute is a composable matcher" do
it "passes" do
expect(record).to be_a_new(record.class).with(
foo: a_string_including("foo"))
end
it "fails" do
message =
if RUBY_VERSION >= '3.4'
"attribute {\"foo\" => (a string matching \"bar\")} was not set on #{record.inspect}"
else
"attribute {\"foo\"=>(a string matching \"bar\")} was not set on #{record.inspect}"
end
expect {
expect(record).to be_a_new(record.class).with(
foo: a_string_matching("bar"))
}.to raise_error(message)
end
context "matcher is wrong type" do
it "fails" do
expect {
expect(record).to be_a_new(record.class).with(
foo: a_hash_including({ no_foo: "foo" }))
}.to raise_error { |e|
expect(e.message).to eq("no implicit conversion of Hash into String").or eq("can't convert Hash into String")
}
end
end
end
context "two attributes are composable matchers" do
context "both matchers present in actual" do
it "passes" do
expect(record).to be_a_new(record.class).with(
foo: a_string_matching("foo"),
bar: a_string_matching("bar")
)
end
end
context "only one matcher present in actual" do
it "fails" do
message =
if RUBY_VERSION >= '3.4'
"attribute {\"bar\" => (a string matching \"barn\")} was not set on #{record.inspect}"
else
"attribute {\"bar\"=>(a string matching \"barn\")} was not set on #{record.inspect}"
end
expect {
expect(record).to be_a_new(record.class).with(
foo: a_string_matching("foo"),
bar: a_string_matching("barn")
)
}.to raise_error(message)
end
end
end
end
context "no attributes same" do
it "fails" do
expect {
expect(record).to be_a_new(record.class).with(zoo: 'zoo', car: 'car')
}.to raise_error { |e|
expect(e.message).to match(/attributes \{.*\} were not set on #{Regexp.escape record.inspect}/)
if RUBY_VERSION >= '3.4'
expect(e.message).to match(/"zoo" => "zoo"/)
expect(e.message).to match(/"car" => "car"/)
else
expect(e.message).to match(/"zoo"=>"zoo"/)
expect(e.message).to match(/"car"=>"car"/)
end
}
end
end
context "one attribute value not the same" do
it "fails" do
message =
if RUBY_VERSION >= '3.4'
%(attribute {"foo" => "bar"} was not set on #{record.inspect})
else
%(attribute {"foo"=>"bar"} was not set on #{record.inspect})
end
expect {
expect(record).to be_a_new(record.class).with(foo: 'bar')
}.to raise_error(message)
end
end
end
context "wrong class and existing record" do
let(:record) do
Class.new do
def initialize(attributes)
@attributes = attributes
end
def attributes
@attributes.stringify_keys
end
def new_record?; false; end
end.new(foo: 'foo', bar: 'bar')
end
context "all attributes same" do
it "fails" do
expect {
expect(record).to be_a_new(String).with(foo: 'foo', bar: 'bar')
}.to raise_error(
"expected #{record.inspect} to be a new String"
)
end
end
context "no attributes same" do
it "fails" do
expect {
expect(record).to be_a_new(String).with(zoo: 'zoo', car: 'car')
}.to raise_error { |e|
expect(e.message).to match(/expected #{Regexp.escape record.inspect} to be a new String and attributes \{.*\} were not set on #{Regexp.escape record.inspect}/)
if RUBY_VERSION >= '3.4'
expect(e.message).to match(/"zoo" => "zoo"/)
expect(e.message).to match(/"car" => "car"/)
else
expect(e.message).to match(/"zoo"=>"zoo"/)
expect(e.message).to match(/"car"=>"car"/)
end
}
end
end
context "one attribute value not the same" do
it "fails" do
message =
"expected #{record.inspect} to be a new String and " +
if RUBY_VERSION >= '3.4'
%(attribute {"foo" => "bar"} was not set on #{record.inspect})
else
%(attribute {"foo"=>"bar"} was not set on #{record.inspect})
end
expect {
expect(record).to be_a_new(String).with(foo: 'bar')
}.to raise_error(message)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/active_job_spec.rb | spec/rspec/rails/matchers/active_job_spec.rb | require "rspec/rails/feature_check"
if RSpec::Rails::FeatureCheck.has_active_job?
require "rspec/rails/matchers/active_job"
class GlobalIdModel
include GlobalID::Identification
attr_reader :id
def self.find(id)
new(id)
end
def initialize(id)
@id = id
end
def ==(comparison_object)
(GlobalIdModel === comparison_object) && (id == comparison_object.id)
end
def to_global_id(_options = {})
@global_id ||= GlobalID.create(self, app: "rspec-suite")
end
end
class FailingGlobalIdModel < GlobalIdModel
def self.find(_id)
raise URI::GID::MissingModelIdError
end
end
end
RSpec.describe "ActiveJob matchers", skip: !RSpec::Rails::FeatureCheck.has_active_job? do
include ActiveSupport::Testing::TimeHelpers
around do |example|
original_logger = ActiveJob::Base.logger
ActiveJob::Base.logger = Logger.new(nil) # Silence messages "[ActiveJob] Enqueued ...".
example.run
ActiveJob::Base.logger = original_logger
end
around do |example|
original_value = RSpec::Mocks.configuration.verify_partial_doubles?
example.run
ensure
RSpec::Mocks.configuration.verify_partial_doubles = original_value
end
let(:heavy_lifting_job) do
Class.new(ActiveJob::Base) do
def perform; end
def self.name; "HeavyLiftingJob"; end
end
end
let(:hello_job) do
Class.new(ActiveJob::Base) do
def perform(*)
end
def self.name; "HelloJob"; end
end
end
let(:logging_job) do
Class.new(ActiveJob::Base) do
def perform; end
def self.name; "LoggingJob"; end
end
end
let(:two_args_job) do
Class.new(ActiveJob::Base) do
def perform(one, two); end
def self.name; "TwoArgsJob"; end
end
end
let(:keyword_args_job) do
Class.new(ActiveJob::Base) do
def perform(one:, two:); end
def self.name; "KeywordArgsJob"; end
end
end
before do
ActiveJob::Base.queue_adapter = :test
end
describe "have_enqueued_job" do
it "raises ArgumentError when no Proc passed to expect" do
expect {
expect(heavy_lifting_job.perform_later).to have_enqueued_job
}.to raise_error(ArgumentError)
end
it "passes with default jobs count (exactly one)" do
expect {
heavy_lifting_job.perform_later
}.to have_enqueued_job
end
it "passes when using alias" do
expect {
heavy_lifting_job.perform_later
}.to enqueue_job
end
it "counts only jobs enqueued in block" do
heavy_lifting_job.perform_later
expect {
heavy_lifting_job.perform_later
}.to have_enqueued_job.exactly(1)
end
it "passes when negated" do
expect { }.not_to have_enqueued_job
end
context "when previously enqueued jobs were performed" do
include ActiveJob::TestHelper
before { stub_const("HeavyLiftingJob", heavy_lifting_job) }
it "counts newly enqueued jobs" do
heavy_lifting_job.perform_later
expect {
perform_enqueued_jobs
hello_job.perform_later
}.to have_enqueued_job(hello_job)
end
end
context "when job is retried" do
include ActiveJob::TestHelper
let(:unreliable_job) do
Class.new(ActiveJob::Base) do
retry_on StandardError, wait: 5, queue: :retry
def self.name; "UnreliableJob"; end
def perform; raise StandardError; end
end
end
before { stub_const("UnreliableJob", unreliable_job) }
it "passes with reenqueued job" do
time = Time.current.change(usec: 0)
travel_to time do
UnreliableJob.perform_later
expect { perform_enqueued_jobs }.to have_enqueued_job(UnreliableJob).on_queue(:retry).at(time + 5)
end
end
end
it "fails when job is not enqueued" do
expect {
expect { }.to have_enqueued_job
}.to fail_with(/expected to enqueue exactly 1 jobs, but enqueued 0/)
end
it "fails when too many jobs enqueued" do
expect {
expect {
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
}.to have_enqueued_job.exactly(1)
}.to fail_with(/expected to enqueue exactly 1 jobs, but enqueued 2/)
end
it "reports correct number in fail error message" do
heavy_lifting_job.perform_later
expect {
expect { }.to have_enqueued_job.exactly(1)
}.to fail_with(/expected to enqueue exactly 1 jobs, but enqueued 0/)
end
it "fails when negated and job is enqueued" do
expect {
expect { heavy_lifting_job.perform_later }.not_to have_enqueued_job
}.to fail_with(/expected not to enqueue at least 1 jobs, but enqueued 1/)
end
it "fails when negated and several jobs enqueued" do
expect {
expect {
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
}.not_to have_enqueued_job
}.to fail_with(/expected not to enqueue at least 1 jobs, but enqueued 2/)
end
it "passes with job name" do
expect {
hello_job.perform_later
heavy_lifting_job.perform_later
}.to have_enqueued_job(hello_job).exactly(1).times
end
it "passes with multiple jobs" do
expect {
hello_job.perform_later
logging_job.perform_later
heavy_lifting_job.perform_later
}.to have_enqueued_job(hello_job).and have_enqueued_job(logging_job)
end
it "passes with :once count" do
expect {
hello_job.perform_later
}.to have_enqueued_job.exactly(:once)
end
it "passes with :twice count" do
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_enqueued_job.exactly(:twice)
end
it "passes with :thrice count" do
expect {
hello_job.perform_later
hello_job.perform_later
hello_job.perform_later
}.to have_enqueued_job.exactly(:thrice)
end
it "passes with at_least count when enqueued jobs are over limit" do
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_enqueued_job.at_least(:once)
end
it "passes with at_most count when enqueued jobs are under limit" do
expect {
hello_job.perform_later
}.to have_enqueued_job.at_most(:once)
end
it "generates failure message with at least hint" do
expect {
expect { }.to have_enqueued_job.at_least(:once)
}.to fail_with(/expected to enqueue at least 1 jobs, but enqueued 0/)
end
it "generates failure message with at most hint" do
expect {
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_enqueued_job.at_most(:once)
}.to fail_with(/expected to enqueue at most 1 jobs, but enqueued 2/)
end
it "passes with provided queue name as string" do
expect {
hello_job.set(queue: "low").perform_later
}.to have_enqueued_job.on_queue("low")
end
it "passes with provided queue name as symbol" do
expect {
hello_job.set(queue: "low").perform_later
}.to have_enqueued_job.on_queue(:low)
end
it "passes with provided priority number as integer" do
expect {
hello_job.set(priority: 2).perform_later
}.to have_enqueued_job.at_priority(2)
end
it "passes with provided priority number as string" do
expect {
hello_job.set(priority: 2).perform_later
}.to have_enqueued_job.at_priority("2")
end
it "fails when the priority wan't set" do
expect {
expect {
hello_job.perform_later
}.to have_enqueued_job.at_priority(2)
}.to fail_with(/expected to enqueue exactly 1 jobs, with priority 2, but enqueued 0.+ with no priority specified/m)
end
it "fails when the priority was set to a different value" do
expect {
expect {
hello_job.set(priority: 1).perform_later
}.to have_enqueued_job.at_priority(2)
}.to fail_with(/expected to enqueue exactly 1 jobs, with priority 2, but enqueued 0.+ with priority 1/m)
end
pending "accepts matchers as arguments to at_priority" do
expect {
hello_job.set(priority: 1).perform_later
}.to have_enqueued_job.at_priority(eq(1))
end
it "passes with provided at date" do
date = Date.tomorrow.noon
expect {
hello_job.set(wait_until: date).perform_later
}.to have_enqueued_job.at(date)
end
it "passes with provided at time" do
time = Time.now + 1.day
expect {
hello_job.set(wait_until: time).perform_later
}.to have_enqueued_job.at(time)
end
it "works with time offsets" do
# NOTE: Time.current does not replicate Rails behavior for 5 seconds from now.
time = Time.current.change(usec: 0)
travel_to time do
expect { hello_job.set(wait: 5).perform_later }.to have_enqueued_job.at(time + 5)
end
end
it "warns when time offsets are inprecise" do
expect(RSpec).to receive(:warn_with).with(/precision error/)
time = Time.current.change(usec: 550)
travel_to time do
expect {
expect { hello_job.set(wait: 5).perform_later }.to have_enqueued_job.at(time + 5)
}.to fail_with(/expected to enqueue exactly 1 jobs/)
end
end
it "accepts composable matchers as an at date" do
future = 1.minute.from_now
slightly_earlier = 58.seconds.from_now
expect {
hello_job.set(wait_until: slightly_earlier).perform_later
}.to have_enqueued_job.at(a_value_within(5.seconds).of(future))
end
it "has an enqueued job when providing at of :no_wait and there is no wait" do
expect {
hello_job.perform_later
}.to have_enqueued_job.at(:no_wait)
end
it "has an enqueued job when providing at and there is no wait" do
date = Date.tomorrow.noon
expect {
expect {
hello_job.perform_later
}.to have_enqueued_job.at(date)
}.to fail_with(/expected to enqueue exactly 1 jobs, at .+ but enqueued 0/)
end
it "has an enqueued job when not providing at and there is a wait" do
date = Date.tomorrow.noon
expect {
hello_job.set(wait_until: date).perform_later
}.to have_enqueued_job
end
it "does not have an enqueued job when providing at of :no_wait and there is a wait" do
date = Date.tomorrow.noon
expect {
hello_job.set(wait_until: date).perform_later
}.to_not have_enqueued_job.at(:no_wait)
end
it "passes with provided arguments" do
expect {
hello_job.perform_later(42, "David")
}.to have_enqueued_job.with(42, "David")
end
describe "verifying the arguments passed match the job's signature" do
it "fails if there is an arity mismatch" do
expect {
expect {
two_args_job.perform_later(1)
}.to have_enqueued_job.with(1)
}.to fail_with(/Incorrect arguments passed to TwoArgsJob: Wrong number of arguments/)
end
it "fails if there is a keyword/positional arguments mismatch" do
expect {
expect {
keyword_args_job.perform_later(1, 2)
}.to have_enqueued_job.with(1, 2)
}.to fail_with(/Incorrect arguments passed to KeywordArgsJob: Missing required keyword arguments/)
end
context "with partial double verification disabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = false
end
it "skips signature checks" do
expect { two_args_job.perform_later(1) }.to have_enqueued_job.with(1)
end
end
context "when partial double verification is temporarily suspended" do
it "skips signature checks" do
without_partial_double_verification {
expect {
two_args_job.perform_later(1)
}.to have_enqueued_job.with(1)
}
end
end
context "without rspec-mocks loaded" do
before do
# Its hard for us to unload this, but its fairly safe to assume that we can run
# a defined? check, this just mocks the "short circuit"
allow(::RSpec::Mocks).to receive(:respond_to?).with(:configuration) { false }
end
it "skips signature checks" do
expect { two_args_job.perform_later(1) }.to have_enqueued_job.with(1)
end
end
end
it "passes with provided arguments containing global id object" do
global_id_object = GlobalIdModel.new("42")
expect {
hello_job.perform_later(global_id_object)
}.to have_enqueued_job.with(global_id_object)
end
it "passes with provided argument matchers" do
expect {
hello_job.perform_later(42, "David")
}.to have_enqueued_job.with(42, "David")
end
it "generates failure message with all provided options" do
date = Date.tomorrow.noon
message = "expected to enqueue exactly 2 jobs, with [42], on queue low, at #{date}, with priority 5, but enqueued 0" \
"\nQueued jobs:" \
"\n HelloJob job with [1], on queue default, with no priority specified"
expect {
expect {
hello_job.perform_later(1)
}.to have_enqueued_job(hello_job).with(42).on_queue("low").at(date).at_priority(5).exactly(2).times
}.to fail_with(message)
end
it "throws descriptive error when no test adapter set" do
queue_adapter = ActiveJob::Base.queue_adapter
ActiveJob::Base.queue_adapter = :inline
expect {
expect { heavy_lifting_job.perform_later }.to have_enqueued_job
}.to raise_error("To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`")
ActiveJob::Base.queue_adapter = queue_adapter
end
it "fails with with block with incorrect data" do
expect {
expect {
hello_job.perform_later("asdf")
}.to have_enqueued_job(hello_job).with { |arg|
expect(arg).to eq("zxcv")
}
}.to raise_error { |e|
expect(e.message).to match(/expected: "zxcv"/)
expect(e.message).to match(/got: "asdf"/)
}
end
it "passes multiple arguments to with block" do
expect {
hello_job.perform_later("asdf", "zxcv")
}.to have_enqueued_job(hello_job).with { |first_arg, second_arg|
expect(first_arg).to eq("asdf")
expect(second_arg).to eq("zxcv")
}
end
it "passes deserialized arguments to with block" do
global_id_object = GlobalIdModel.new("42")
expect {
hello_job.perform_later(global_id_object, symbolized_key: "asdf")
}.to have_enqueued_job(hello_job).with { |first_arg, second_arg|
expect(first_arg).to eq(global_id_object)
expect(second_arg).to eq({ symbolized_key: "asdf" })
}
end
it "ignores undeserializable arguments" do
failing_global_id_object = FailingGlobalIdModel.new("21")
global_id_object = GlobalIdModel.new("42")
expect {
hello_job.perform_later(failing_global_id_object)
hello_job.perform_later(global_id_object)
}.to have_enqueued_job(hello_job).with(global_id_object)
end
it "only calls with block if other conditions are met" do
noon = Date.tomorrow.noon
midnight = Date.tomorrow.midnight
expect {
hello_job.set(wait_until: noon).perform_later("asdf")
hello_job.set(wait_until: midnight).perform_later("zxcv")
}.to have_enqueued_job(hello_job).at(noon).with { |arg|
expect(arg).to eq("asdf")
}
end
it "passes with Time" do
usec_time = Time.iso8601('2016-07-01T00:00:00.000001Z')
expect {
hello_job.perform_later(usec_time)
}.to have_enqueued_job(hello_job).with(usec_time)
end
it "passes with ActiveSupport::TimeWithZone" do
usec_time = Time.iso8601('2016-07-01T00:00:00.000001Z').in_time_zone
expect {
hello_job.perform_later(usec_time)
}.to have_enqueued_job(hello_job).with(usec_time)
end
end
describe "have_been_enqueued" do
before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear }
it "raises RSpec::Expectations::ExpectationNotMetError when Proc passed to expect" do
expect {
expect { heavy_lifting_job }.to have_been_enqueued
}.to raise_error(RSpec::Expectations::ExpectationNotMetError)
end
it "passes with default jobs count (exactly one)" do
heavy_lifting_job.perform_later
expect(heavy_lifting_job).to have_been_enqueued
end
it "counts all enqueued jobs" do
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
expect(heavy_lifting_job).to have_been_enqueued.exactly(2)
end
it "passes when negated" do
expect(heavy_lifting_job).not_to have_been_enqueued
end
it "fails when job is not enqueued" do
expect {
expect(heavy_lifting_job).to have_been_enqueued
}.to fail_with(/expected to enqueue exactly 1 jobs, but enqueued 0/)
end
describe "verifying the arguments passed match the job's signature" do
it "fails if there is an arity mismatch" do
two_args_job.perform_later(1)
expect {
expect(two_args_job).to have_been_enqueued.with(1)
}.to fail_with(/Incorrect arguments passed to TwoArgsJob: Wrong number of arguments/)
end
it "fails if there is a keyword/positional arguments mismatch" do
keyword_args_job.perform_later(1, 2)
expect {
expect(keyword_args_job).to have_been_enqueued.with(1, 2)
}.to fail_with(/Incorrect arguments passed to KeywordArgsJob: Missing required keyword arguments/)
end
context "with partial double verification disabled" do
before do
RSpec::Mocks.configuration.verify_partial_doubles = false
end
it "skips signature checks" do
keyword_args_job.perform_later(1, 2)
expect(keyword_args_job).to have_been_enqueued.with(1, 2)
end
end
context "when partial double verification is temporarily suspended" do
it "skips signature checks" do
keyword_args_job.perform_later(1, 2)
without_partial_double_verification {
expect(keyword_args_job).to have_been_enqueued.with(1, 2)
}
end
end
end
it "fails when negated and several jobs enqueued" do
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
expect {
expect(heavy_lifting_job).not_to have_been_enqueued
}.to fail_with(/expected not to enqueue at least 1 jobs, but enqueued 2/)
end
it "accepts composable matchers as an at date" do
future = 1.minute.from_now
slightly_earlier = 58.seconds.from_now
heavy_lifting_job.set(wait_until: slightly_earlier).perform_later
expect(heavy_lifting_job)
.to have_been_enqueued.at(a_value_within(5.seconds).of(future))
end
end
describe "have_performed_job" do
before do
ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
# stub_const is used so `job_data["job_class"].constantize` works
stub_const('HeavyLiftingJob', heavy_lifting_job)
stub_const('HelloJob', hello_job)
stub_const('LoggingJob', logging_job)
end
it "raises ArgumentError when no Proc passed to expect" do
expect {
expect(heavy_lifting_job.perform_later).to have_performed_job
}.to raise_error(ArgumentError)
end
it "passes with default jobs count (exactly one)" do
expect {
heavy_lifting_job.perform_later
}.to have_performed_job
end
it "counts only jobs performed in block" do
heavy_lifting_job.perform_later
expect {
heavy_lifting_job.perform_later
}.to have_performed_job.exactly(1)
end
it "passes when negated" do
expect { }.not_to have_performed_job
end
it "fails when job is not performed" do
expect {
expect { }.to have_performed_job
}.to fail_with(/expected to perform exactly 1 jobs, but performed 0/)
end
it "fails when too many jobs performed" do
expect {
expect {
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
}.to have_performed_job.exactly(1)
}.to fail_with(/expected to perform exactly 1 jobs, but performed 2/)
end
it "reports correct number in fail error message" do
heavy_lifting_job.perform_later
expect {
expect { }.to have_performed_job.exactly(1)
}.to fail_with(/expected to perform exactly 1 jobs, but performed 0/)
end
it "fails when negated and job is performed" do
expect {
expect { heavy_lifting_job.perform_later }.not_to have_performed_job
}.to fail_with(/expected not to perform exactly 1 jobs, but performed 1/)
end
it "passes with job name" do
expect {
hello_job.perform_later
heavy_lifting_job.perform_later
}.to have_performed_job(hello_job).exactly(1).times
end
it "passes with multiple jobs" do
expect {
hello_job.perform_later
logging_job.perform_later
heavy_lifting_job.perform_later
}.to have_performed_job(hello_job).and have_performed_job(logging_job)
end
it "passes with :once count" do
expect {
hello_job.perform_later
}.to have_performed_job.exactly(:once)
end
it "passes with :twice count" do
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_performed_job.exactly(:twice)
end
it "passes with :thrice count" do
expect {
hello_job.perform_later
hello_job.perform_later
hello_job.perform_later
}.to have_performed_job.exactly(:thrice)
end
it "passes with at_least count when performed jobs are over limit" do
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_performed_job.at_least(:once)
end
it "passes with at_most count when performed jobs are under limit" do
expect {
hello_job.perform_later
}.to have_performed_job.at_most(:once)
end
it "generates failure message with at least hint" do
expect {
expect { }.to have_performed_job.at_least(:once)
}.to fail_with(/expected to perform at least 1 jobs, but performed 0/)
end
it "generates failure message with at most hint" do
expect {
expect {
hello_job.perform_later
hello_job.perform_later
}.to have_performed_job.at_most(:once)
}.to fail_with(/expected to perform at most 1 jobs, but performed 2/)
end
it "passes with provided queue name as string" do
expect {
hello_job.set(queue: "low").perform_later
}.to have_performed_job.on_queue("low")
end
it "passes with provided queue name as symbol" do
expect {
hello_job.set(queue: "low").perform_later
}.to have_performed_job.on_queue(:low)
end
it "passes with provided at date" do
date = Date.tomorrow.noon
expect {
hello_job.set(wait_until: date).perform_later
}.to have_performed_job.at(date)
end
it "passes with provided arguments" do
expect {
hello_job.perform_later(42, "David")
}.to have_performed_job.with(42, "David")
end
it "passes with provided arguments containing global id object" do
global_id_object = GlobalIdModel.new("42")
expect {
hello_job.perform_later(global_id_object)
}.to have_performed_job.with(global_id_object)
end
it "passes with provided argument matchers" do
expect {
hello_job.perform_later(42, "David")
}.to have_performed_job.with(42, "David")
end
it "generates failure message with all provided options" do
date = Date.tomorrow.noon
message = "expected to perform exactly 2 jobs, with [42], on queue low, at #{date}, with priority 5, but performed 0" \
"\nQueued jobs:" \
"\n HelloJob job with [1], on queue default, with no priority specified"
expect {
expect {
hello_job.perform_later(1)
}.to have_performed_job(hello_job).with(42).on_queue("low").at(date).at_priority(5).exactly(2).times
}.to fail_with(message)
end
it "throws descriptive error when no test adapter set" do
queue_adapter = ActiveJob::Base.queue_adapter
ActiveJob::Base.queue_adapter = :inline
expect {
expect { heavy_lifting_job.perform_later }.to have_performed_job
}.to raise_error("To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`")
ActiveJob::Base.queue_adapter = queue_adapter
end
it "fails with with block with incorrect data" do
expect {
expect {
hello_job.perform_later("asdf")
}.to have_performed_job(hello_job).with { |arg|
expect(arg).to eq("zxcv")
}
}.to raise_error { |e|
expect(e.message).to match(/expected: "zxcv"/)
expect(e.message).to match(/got: "asdf"/)
}
end
it "passes multiple arguments to with block" do
expect {
hello_job.perform_later("asdf", "zxcv")
}.to have_performed_job(hello_job).with { |first_arg, second_arg|
expect(first_arg).to eq("asdf")
expect(second_arg).to eq("zxcv")
}
end
it "passes deserialized arguments to with block" do
global_id_object = GlobalIdModel.new("42")
expect {
hello_job.perform_later(global_id_object, symbolized_key: "asdf")
}.to have_performed_job(hello_job).with { |first_arg, second_arg|
expect(first_arg).to eq(global_id_object)
expect(second_arg).to eq({ symbolized_key: "asdf" })
}
end
it "only calls with block if other conditions are met" do
noon = Date.tomorrow.noon
midnight = Date.tomorrow.midnight
expect {
hello_job.set(wait_until: noon).perform_later("asdf")
hello_job.set(wait_until: midnight).perform_later("zxcv")
}.to have_performed_job(hello_job).at(noon).with { |arg|
expect(arg).to eq("asdf")
}
end
end
describe "have_been_performed" do
before do
ActiveJob::Base.queue_adapter.performed_jobs.clear
ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
stub_const('HeavyLiftingJob', heavy_lifting_job)
end
it "raises RSpec::Expectations::ExpectationNotMetError when Proc passed to expect" do
expect {
expect { heavy_lifting_job }.to have_been_performed
}.to raise_error(RSpec::Expectations::ExpectationNotMetError)
end
it "passes with default jobs count (exactly one)" do
heavy_lifting_job.perform_later
expect(heavy_lifting_job).to have_been_performed
end
it "counts all performed jobs" do
heavy_lifting_job.perform_later
heavy_lifting_job.perform_later
expect(heavy_lifting_job).to have_been_performed.exactly(2)
end
it "passes when negated" do
expect(heavy_lifting_job).not_to have_been_performed
end
it "fails when job is not performed" do
expect {
expect(heavy_lifting_job).to have_been_performed
}.to fail_with(/expected to perform exactly 1 jobs, but performed 0/)
end
end
describe 'Active Job test helpers' do
include ActiveJob::TestHelper
it 'does not raise that "assert_nothing_raised" is undefined' do
expect {
perform_enqueued_jobs do
:foo
end
}.to_not raise_error
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/have_rendered_spec.rb | spec/rspec/rails/matchers/have_rendered_spec.rb | %w[have_rendered render_template].each do |template_expectation|
RSpec.describe template_expectation do
include RSpec::Rails::Matchers::RenderTemplate
let(:response) { ActionDispatch::TestResponse.new }
context "given a hash" do
def assert_template(*); end
it "delegates to assert_template" do
expect(self).to receive(:assert_template).with({ this: "hash" }, "this message")
expect("response").to send(template_expectation, { this: "hash" }, "this message")
end
end
context "given a string" do
def assert_template(*); end
it "delegates to assert_template" do
expect(self).to receive(:assert_template).with("this string", "this message")
expect("response").to send(template_expectation, "this string", "this message")
end
end
context "given a symbol" do
def assert_template(*); end
it "converts to_s and delegates to assert_template" do
expect(self).to receive(:assert_template).with("template_name", "this message")
expect("response").to send(template_expectation, :template_name, "this message")
end
end
context "with should" do
context "when assert_template passes" do
def assert_template(*); end
it "passes" do
expect do
expect(response).to send(template_expectation, "template_name")
end.to_not raise_exception
end
end
context "when assert_template fails" do
it "uses failure message from assert_template" do
def assert_template(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
expect do
expect(response).to send(template_expectation, "template_name")
end.to raise_error("this message")
end
end
context "when fails due to some other exception" do
it "raises that exception" do
def assert_template(*)
raise "oops"
end
expect do
expect(response).to send(template_expectation, "template_name")
end.to raise_exception("oops")
end
end
end
context "with should_not" do
context "when assert_template fails" do
it "passes" do
def assert_template(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
expect do
expect(response).to_not send(template_expectation, "template_name")
end.to_not raise_exception
end
end
context "when assert_template passes" do
it "fails with custom failure message" do
def assert_template(*); end
expect do
expect(response).to_not send(template_expectation, "template_name")
end.to raise_error(/expected not to render "template_name", but did/)
end
end
context "when fails due to some other exception" do
it "raises that exception" do
def assert_template(*); raise "oops"; end
expect do
expect(response).to_not send(template_expectation, "template_name")
end.to raise_exception("oops")
end
end
context "when fails with a redirect" do
let(:response) { ActionDispatch::TestResponse.new(303) }
def assert_template(*)
message = "expecting <'template_name'> but rendering with <[]>"
raise ActiveSupport::TestCase::Assertion, message
end
def normalize_argument_to_redirection(_response_redirect_location)
"http://test.host/widgets/1"
end
it "gives informative error message" do
response = ActionDispatch::TestResponse.new(302)
response.location = "http://test.host/widgets/1"
expect do
expect(response).to send(template_expectation, "template_name")
end.to raise_exception("expecting <'template_name'> but was a redirect to <http://test.host/widgets/1>")
end
context 'with a badly formatted error message' do
def assert_template(*)
message = 'expected [] to include "some/path"'
raise ActiveSupport::TestCase::Assertion, message
end
it 'falls back to something informative' do
expect do
expect(response).to send(template_expectation, "template_name")
end.to raise_exception('expected [] to include "some/path" but was a redirect to <http://test.host/widgets/1>')
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/redirect_to_spec.rb | spec/rspec/rails/matchers/redirect_to_spec.rb | require "active_support"
require "active_support/test_case"
RSpec.describe "redirect_to" do
include RSpec::Rails::Matchers::RedirectTo
let(:response) { ActionDispatch::TestResponse.new }
context "with should" do
context "when assert_redirected_to passes" do
def assert_redirected_to(*); end
it "passes" do
expect do
expect(response).to redirect_to("destination")
end.to_not raise_exception
end
end
context "when assert_redirected_to fails" do
def assert_redirected_to(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
it "uses failure message from assert_redirected_to" do
expect do
expect(response).to redirect_to("destination")
end.to raise_exception("this message")
end
end
context "when fails due to some other exception" do
def assert_redirected_to(*)
raise "oops"
end
it "raises that exception" do
expect do
expect(response).to redirect_to("destination")
end.to raise_exception("oops")
end
end
end
context "with should_not" do
context "when assert_redirected_to fails" do
def assert_redirected_to(*)
raise ActiveSupport::TestCase::Assertion, "this message"
end
it "passes" do
expect do
expect(response).not_to redirect_to("destination")
end.to_not raise_exception
end
end
context "when assert_redirected_to passes" do
def assert_redirected_to(*); end
it "fails with custom failure message" do
expect do
expect(response).not_to redirect_to("destination")
end.to raise_exception(/expected not to redirect to "destination", but did/)
end
end
context "when fails due to some other exception" do
def assert_redirected_to(*)
raise "oops"
end
it "raises that exception" do
expect do
expect(response).not_to redirect_to("destination")
end.to raise_exception("oops")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/action_cable/have_stream_spec.rb | spec/rspec/rails/matchers/action_cable/have_stream_spec.rb | require "rspec/rails/feature_check"
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
class StreamModel < Struct.new(:id)
def to_gid_param
"StreamModel##{id}"
end
end
class StreamChannel < ActionCable::Channel::Base
def self.channel_name
"broadcast"
end
def subscribed
stream_from "chat_#{params[:id]}" if params[:id]
stream_for StreamModel.new(params[:user]) if params[:user]
end
end
end
RSpec.describe "have_stream matchers", skip: !RSpec::Rails::FeatureCheck.has_action_cable_testing? do
include RSpec::Rails::ChannelExampleGroup
tests StreamChannel if respond_to?(:tests)
before { stub_connection }
describe "have_streams" do
it "raises when no subscription started" do
expect {
expect(subscription).to have_streams
}.to raise_error(/Must be subscribed!/)
end
it "does not allow usage" do
subscribe
expect {
expect(subscription).to have_streams
}.to raise_error(ArgumentError, /have_streams is used for negated expectations only/)
end
context "with negated form" do
it "raises when no subscription started" do
expect {
expect(subscription).not_to have_streams
}.to raise_error(/Must be subscribed!/)
end
it "raises ArgumentError when no subscription passed to expect" do
subscribe id: 1
expect {
expect(true).not_to have_streams
}.to raise_error(ArgumentError)
end
it "passes with negated form" do
subscribe
expect(subscription).not_to have_streams
end
it "fails with message" do
subscribe id: 1
expect {
expect(subscription).not_to have_streams
}.to raise_error(/expected not to have any stream started/)
end
end
end
describe "have_stream_from" do
it "raises when no subscription started" do
expect {
expect(subscription).to have_stream_from("stream")
}.to raise_error(/Must be subscribed!/)
end
it "raises ArgumentError when no subscription passed to expect" do
subscribe id: 1
expect {
expect(true).to have_stream_from("stream")
}.to raise_error(ArgumentError)
end
it "passes" do
subscribe id: 1
expect(subscription).to have_stream_from("chat_1")
end
it "fails with message" do
subscribe id: 1
expect {
expect(subscription).to have_stream_from("chat_2")
}.to raise_error(/expected to have stream "chat_2" started, but have \["chat_1"\]/)
end
context "with negated form" do
it "passes" do
subscribe id: 1
expect(subscription).not_to have_stream_from("chat_2")
end
it "fails with message" do
subscribe id: 1
expect {
expect(subscription).not_to have_stream_from("chat_1")
}.to raise_error(/expected not to have stream "chat_1" started, but have \["chat_1"\]/)
end
end
context "with composable matcher" do
it "passes" do
subscribe id: 1
expect(subscription).to have_stream_from(a_string_starting_with("chat"))
end
it "fails with message" do
subscribe id: 1
expect {
expect(subscription).to have_stream_from(a_string_starting_with("room"))
}.to raise_error(/expected to have stream a string starting with "room" started, but have \["chat_1"\]/)
end
end
end
describe "have_stream_for" do
it "raises when no subscription started" do
expect {
expect(subscription).to have_stream_for(StreamModel.new(42))
}.to raise_error(/Must be subscribed!/)
end
it "raises ArgumentError when no subscription passed to expect" do
subscribe user: 42
expect {
expect(true).to have_stream_for(StreamModel.new(42))
}.to raise_error(ArgumentError)
end
it "passes" do
subscribe user: 42
expect(subscription).to have_stream_for(StreamModel.new(42))
end
it "fails with message" do
subscribe user: 42
broadcast_preamble =
if Rails.version.to_f < 8.1
"broadcast:StreamModel#"
else
"broadcast:"
end
expect {
expect(subscription).to have_stream_for(StreamModel.new(31_337))
}.to raise_error(/expected to have stream "#{broadcast_preamble}31337" started, but have \["#{broadcast_preamble}42"\]/)
end
context "with negated form" do
it "passes" do
subscribe user: 42
expect(subscription).not_to have_stream_for(StreamModel.new(31_337))
end
it "fails with message" do
subscribe user: 42
broadcast_id =
if Rails.version.to_f < 8.1
"broadcast:StreamModel#42"
else
"broadcast:42"
end
expect {
expect(subscription).not_to have_stream_for(StreamModel.new(42))
}.to raise_error(/expected not to have stream "#{broadcast_id}" started, but have \["#{broadcast_id}"\]/)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/rspec/rails/matchers/action_cable/have_broadcasted_to_spec.rb | spec/rspec/rails/matchers/action_cable/have_broadcasted_to_spec.rb | require "rspec/rails/feature_check"
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
require "rspec/rails/matchers/action_cable"
class CableGlobalIdModel
include GlobalID::Identification
attr_reader :id
def initialize(id)
@id = id
end
def to_global_id(_options = {})
@global_id ||= GlobalID.create(self, app: "rspec-suite")
end
end
end
RSpec.describe "have_broadcasted_to matchers", skip: !RSpec::Rails::FeatureCheck.has_action_cable_testing? do
let(:channel) do
Class.new(ActionCable::Channel::Base) do
def self.channel_name
"broadcast"
end
end
end
def broadcast(stream, msg)
ActionCable.server.broadcast stream, msg
end
before do
server = ActionCable.server
test_adapter = ActionCable::SubscriptionAdapter::Test.new(server)
server.instance_variable_set(:@pubsub, test_adapter)
end
describe "have_broadcasted_to" do
it "raises ArgumentError when no Proc passed to expect" do
expect {
expect(true).to have_broadcasted_to('stream')
}.to raise_error(ArgumentError)
end
it "passes with default messages count (exactly one)" do
expect {
broadcast('stream', 'hello')
}.to have_broadcasted_to('stream')
end
it "passes when using symbol target" do
expect {
broadcast(:stream, 'hello')
}.to have_broadcasted_to(:stream)
end
it "passes when using alias" do
expect {
broadcast('stream', 'hello')
}.to broadcast_to('stream')
end
it "counts only messages sent in block" do
broadcast('stream', 'one')
expect {
broadcast('stream', 'two')
}.to have_broadcasted_to('stream').exactly(1)
end
it "passes when negated" do
expect { }.not_to have_broadcasted_to('stream')
end
it "fails when message is not sent" do
expect {
expect { }.to have_broadcasted_to('stream')
}.to raise_error(/expected to broadcast exactly 1 messages to stream, but broadcast 0/)
end
it "fails when too many messages broadcast" do
expect {
expect {
broadcast('stream', 'one')
broadcast('stream', 'two')
}.to have_broadcasted_to('stream').exactly(1)
}.to raise_error(/expected to broadcast exactly 1 messages to stream, but broadcast 2/)
end
it "reports correct number in fail error message" do
broadcast('stream', 'one')
expect {
expect { }.to have_broadcasted_to('stream').exactly(1)
}.to raise_error(/expected to broadcast exactly 1 messages to stream, but broadcast 0/)
end
it "fails when negated and message is sent" do
expect {
expect { broadcast('stream', 'one') }.not_to have_broadcasted_to('stream')
}.to raise_error(/expected not to broadcast exactly 1 messages to stream, but broadcast 1/)
end
it "passes with multiple streams" do
expect {
broadcast('stream_a', 'A')
broadcast('stream_b', 'B')
broadcast('stream_c', 'C')
}.to have_broadcasted_to('stream_a').and have_broadcasted_to('stream_b')
end
it "passes with :once count" do
expect {
broadcast('stream', 'one')
}.to have_broadcasted_to('stream').exactly(:once)
end
it "passes with :twice count" do
expect {
broadcast('stream', 'one')
broadcast('stream', 'two')
}.to have_broadcasted_to('stream').exactly(:twice)
end
it "passes with :thrice count" do
expect {
broadcast('stream', 'one')
broadcast('stream', 'two')
broadcast('stream', 'three')
}.to have_broadcasted_to('stream').exactly(:thrice)
end
it "passes with at_least count when sent messages are over limit" do
expect {
broadcast('stream', 'one')
broadcast('stream', 'two')
}.to have_broadcasted_to('stream').at_least(:once)
end
it "passes with at_most count when sent messages are under limit" do
expect {
broadcast('stream', 'hello')
}.to have_broadcasted_to('stream').at_most(:once)
end
it "generates failure message with at least hint" do
expect {
expect { }.to have_broadcasted_to('stream').at_least(:once)
}.to raise_error(/expected to broadcast at least 1 messages to stream, but broadcast 0/)
end
it "generates failure message with at most hint" do
expect {
expect {
broadcast('stream', 'hello')
broadcast('stream', 'hello')
}.to have_broadcasted_to('stream').at_most(:once)
}.to raise_error(/expected to broadcast at most 1 messages to stream, but broadcast 2/)
end
it "passes with provided data" do
expect {
broadcast('stream', id: 42, name: "David")
}.to have_broadcasted_to('stream').with(id: 42, name: "David")
end
it "passes with provided data matchers" do
expect {
broadcast('stream', id: 42, name: "David", message_id: 123)
}.to have_broadcasted_to('stream').with(a_hash_including(name: "David", id: 42))
end
it "passes with provided data matchers with anything" do
expect {
broadcast('stream', id: 42, name: "David", message_id: 123)
}.to have_broadcasted_to('stream').with({ name: anything, id: anything, message_id: anything })
end
it "generates failure message when data not match" do
expect {
expect {
broadcast('stream', id: 42, name: "David", message_id: 123)
}.to have_broadcasted_to('stream').with(a_hash_including(name: "John", id: 42))
}.to raise_error(/expected to broadcast exactly 1 messages to stream with a hash including/)
end
it "throws descriptive error when no test adapter set" do
require "action_cable/subscription_adapter/inline"
ActionCable.server.instance_variable_set(:@pubsub, ActionCable::SubscriptionAdapter::Inline)
expect {
expect { broadcast('stream', 'hello') }.to have_broadcasted_to('stream')
}.to raise_error("To use ActionCable matchers set `adapter: test` in your cable.yml")
end
it "fails with with block with incorrect data" do
expect {
expect {
broadcast('stream', "asdf")
}.to have_broadcasted_to('stream').with { |data|
expect(data).to eq("zxcv")
}
}.to raise_error { |e|
expect(e.message).to match(/expected: "zxcv"/)
expect(e.message).to match(/got: "asdf"/)
}
end
context "when object is passed as first argument" do
let(:model) { CableGlobalIdModel.new(42) }
context "when channel is present" do
it "passes" do
expect {
channel.broadcast_to(model, text: 'Hi')
}.to have_broadcasted_to(model).from_channel(channel)
end
end
context "when channel can't be inferred" do
it "raises exception" do
expect {
expect {
channel.broadcast_to(model, text: 'Hi')
}.to have_broadcasted_to(model)
}.to raise_error(ArgumentError)
end
end
end
it "has an appropriate description" do
expect(have_broadcasted_to("my_stream").description).to eq("have broadcasted exactly 1 messages to my_stream")
end
it "has an appropriate description when aliased" do
expect(broadcast_to("my_stream").description).to eq("broadcast exactly 1 messages to my_stream")
end
it "has an appropriate description when stream name is passed as an array" do
expect(have_broadcasted_to(%w[my_stream stream_2]).from_channel(channel).description).to eq("have broadcasted exactly 1 messages to broadcast:my_stream:stream_2")
end
it "has an appropriate description not mentioning the channel when qualified with `#from_channel`" do
expect(have_broadcasted_to("my_stream").from_channel(channel).description).to eq("have broadcasted exactly 1 messages to my_stream")
end
it "has an appropriate description including the expected contents when qualified with `#with`" do
expect(have_broadcasted_to("my_stream").from_channel(channel).with("hello world").description).to eq("have broadcasted exactly 1 messages to my_stream with \"hello world\"")
end
it "has an appropriate description including the matcher's description when qualified with `#with` and a composable matcher" do
description = have_broadcasted_to("my_stream")
.from_channel(channel)
.with(a_hash_including(a: :b))
.description
if RUBY_VERSION >= '3.4'
expect(description).to eq("have broadcasted exactly 1 messages to my_stream with a hash including {a: :b}")
else
expect(description).to eq("have broadcasted exactly 1 messages to my_stream with a hash including {:a => :b}")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.