Development
- + +7.0.2 / 2024-11-09
+Bug Fixes:
- Fix issue with
have_enqueued_mail
when jobs were incorrectly matched due @@ -1324,7 +1326,7 @@2.0.0 / 2010-10-10
diff --git a/source/documentation/7.0/rspec-rails/RSpec.html b/source/documentation/7.0/rspec-rails/RSpec.html index 1957d269a..0f97c737f 100644 --- a/source/documentation/7.0/rspec-rails/RSpec.html +++ b/source/documentation/7.0/rspec-rails/RSpec.html @@ -62,7 +62,7 @@
More precise expectation with a
'7.0.1'
'7.0.2'
Consult the official Upgrading from Capybara 2.x to 3.x guide.
diff --git a/source/documentation/7.0/rspec-rails/file.Changelog.html b/source/documentation/7.0/rspec-rails/file.Changelog.html index 5fa47a48b..a6340e63d 100644 --- a/source/documentation/7.0/rspec-rails/file.Changelog.html +++ b/source/documentation/7.0/rspec-rails/file.Changelog.html @@ -41,7 +41,9 @@Bug Fixes:
have_enqueued_mail
when jobs were incorrectly matched due
@@ -1324,7 +1326,7 @@ rubocop: disable Metrics/ClassLength
++ Modules: Rails +
+Namespace for rspec-rails code.
++ Modules: ChannelExampleGroup, ControllerExampleGroup, FeatureExampleGroup, HelperExampleGroup, JobExampleGroup, MailboxExampleGroup, MailerExampleGroup, Matchers, ModelExampleGroup, RailsExampleGroup, RequestExampleGroup, RoutingExampleGroup, SystemExampleGroup, Version, ViewAssigns, ViewExampleGroup, ViewRendering, ViewSpecMethods + Classes: ActiveRecordConfiguration, Configuration, Railtie, ViewPathBuilder +
+Constant aliased to either Minitest or TestUnit, depending on what is +loaded.
+Minitest::Assertions
+ This constant is part of a private API. + You should avoid using this constant if possible, as it may be removed or be changed in the future. +
+Mappings used by infer_spec_type_from_file_location!
.
{ + channel: %w[spec channels], + controller: %w[spec controllers], + generator: %w[spec generator], + helper: %w[spec helpers], + job: %w[spec jobs], + mailer: %w[spec mailers], + model: %w[spec models], + request: %w[spec (requests|integration|api)], + routing: %w[spec routing], + view: %w[spec views], + feature: %w[spec features], + system: %w[spec system], + mailbox: %w[spec mailboxes] +}
Sets up the different example group modules for the different spec types.
+Automatically tag specs in conventional directories with matching type
metadata so that they have relevant helpers available to them.
Enables view rendering for controllers specs.
+When set to true
, controller specs will render the relevant view as well.
Reader for currently value of render_views
setting.
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Sets up the different example group modules for the different spec types
+
+ +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57+ |
+
+ # File 'lib/rspec/rails/configuration.rb', line 47 +def self.add_test_type_configurations(config) + config.include RSpec::Rails::ControllerExampleGroup, type: :controller + config.include RSpec::Rails::HelperExampleGroup, type: :helper + config.include RSpec::Rails::ModelExampleGroup, type: :model + config.include RSpec::Rails::RequestExampleGroup, type: :request + config.include RSpec::Rails::RoutingExampleGroup, type: :routing + config.include RSpec::Rails::ViewExampleGroup, type: :view + config.include RSpec::Rails::FeatureExampleGroup, type: :feature + config.include RSpec::Rails::Matchers + config.include RSpec::Rails::SystemExampleGroup, type: :system +end+ |
+
Automatically tag specs in conventional directories with matching type
+metadata so that they have relevant helpers available to them. See
+RSpec::Rails::DIRECTORY_MAPPINGS
for details on which metadata is
+applied to each directory.
+ ++ |
+
+ # File 'lib/rspec/rails/configuration.rb', line 7
+
+ |
+
Enables view rendering for controllers specs.
+
+ ++ |
+
+ # File 'lib/rspec/rails/configuration.rb', line 18
+
+ |
+
When set to true
, controller specs will render the relevant view as
+well. Defaults to false
.
+ ++ |
+
+ # File 'lib/rspec/rails/configuration.rb', line 13
+
+ |
+
Reader for currently value of render_views
setting.
+ ++ |
+
+ # File 'lib/rspec/rails/configuration.rb', line 21
+
+ |
+
Fake class to document RSpec ActiveRecord configuration options. In practice, +these are dynamically added to the normal RSpec configuration object.
+Container module for channel spec functionality.
++ Modules: ClassMethods +
+Checks that the connection attempt has been rejected.
+Checks that the channel has been subscribed to a stream for the given model.
+Checks that the channel has been subscribed to the given stream.
+Checks that the subscription is subscribed to at least one stream.
+Checks that the connection attempt has been rejected.
+
+ +58 +59 +60+ |
+
+ # File 'lib/rspec/rails/example/channel_example_group.rb', line 58 +def have_rejected_connection + raise_error(::ActionCable::Connection::Authorization::UnauthorizedError) +end+ |
+
Checks that the channel has been subscribed to a stream for the given model
+
+ +86 +87 +88 +89+ |
+
+ # File 'lib/rspec/rails/example/channel_example_group.rb', line 86 +def have_stream_for(object) + check_subscribed! + RSpec::Rails::Matchers::ActionCable::HaveStream.new(broadcasting_for(object)) +end+ |
+
Checks that the channel has been subscribed to the given stream
+
+ +76 +77 +78 +79 +80+ |
+
+ # File 'lib/rspec/rails/example/channel_example_group.rb', line 76 +def have_stream_from(stream) + check_subscribed! + RSpec::Rails::Matchers::ActionCable::HaveStream.new(stream) +end+ |
+
Checks that the subscription is subscribed to at least one stream.
+
+ +66 +67 +68 +69 +70+ |
+
+ # File 'lib/rspec/rails/example/channel_example_group.rb', line 66 +def have_streams + check_subscribed! + RSpec::Rails::Matchers::ActionCable::HaveStream.new +end+ |
+
Class-level DSL for channel specs.
+Fake class to document RSpec Rails configuration options. In practice, +these are dynamically added to the normal RSpec configuration object.
+Container module for controller spec functionality.
++ Modules: ClassMethods +
+Returns the controller object instance under test.
+Returns the Rails routes used for the spec.
+Extends the controller with a module that overrides rescue_with_handler
to raise the exception passed to it.
If method is a named_route, delegates to the RouteSet associated with this controller.
++ This class handles dynamic methods through the method_missing method +
+If method is a named_route, delegates to the RouteSet associated with +this controller.
+
+ +172 +173 +174 +175 +176 +177 +178+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 172 +def method_missing(method, *args, &block) + if route_available?(method) + controller.send(method, *args, &block) + else + super + end +end+ |
+
Returns the controller object instance under test.
+
+ +128 +129 +130+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 128 +def controller + @controller +end+ |
+
Returns the Rails routes used for the spec.
+
+ +132 +133 +134+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 132 +def routes + @routes +end+ |
+
Extends the controller with a module that overrides
+rescue_with_handler
to raise the exception passed to it. Use this to
+specify that an action should raise an exception given appropriate
+conditions.
+ +166 +167 +168+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 166 +def bypass_rescue + controller.extend(BypassRescue) +end+ |
+
Class-level DSL for controller specs.
+Supports a simple DSL for specifying behavior of ApplicationController.
+Specifies the routeset that will be used for the example group.
+Due to Ruby 1.8 scoping rules in anonymous subclasses, constants
+defined in ApplicationController
must be fully qualified (e.g.
+ApplicationController::AccessDenied
) in the block passed to the
+controller
method. Any instance methods, filters, etc, that are
+defined in ApplicationController
, however, are accessible from
+within the block.
Supports a simple DSL for specifying behavior of ApplicationController.
+Creates an anonymous subclass of ApplicationController and evals the
+body
in that context. Also sets up implicit routes for this
+controller, that are separate from those defined in "config/routes.rb".
If you would like to spec a subclass of ApplicationController, call +controller like so:
+controller(ApplicationControllerSubclass) do
+ # ....
+end
+
+
+ +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 61 +def controller(base_class = nil, &body) + if RSpec.configuration.infer_base_class_for_anonymous_controllers? + base_class ||= controller_class + end + base_class ||= defined?(ApplicationController) ? ApplicationController : ActionController::Base + new_controller_class = Class.new(base_class) do + def self.name + root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base + if superclass == root_controller || superclass.abstract? + "AnonymousController" + else + superclass.name + end + end + end + new_controller_class.class_exec(&body) + (class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class } + before do + @orig_routes = routes + resource_name = if @controller.respond_to?(:controller_name) + @controller.controller_name.to_sym + else + :anonymous + end + resource_path = if @controller.respond_to?(:controller_path) + @controller.controller_path + else + resource_name.to_s + end + resource_module = resource_path.rpartition('/').first.presence + resource_as = 'anonymous_' + resource_path.tr('/', '_') + self.routes = ActionDispatch::Routing::RouteSet.new.tap do |r| + r.draw do + resources resource_name, + as: resource_as, + module: resource_module, + path: resource_path + end + end + end + after do + self.routes = @orig_routes + @orig_routes = nil + end +end+ |
+
Specifies the routeset that will be used for the example group. This +is most useful when testing Rails engines.
+
+ +119 +120 +121 +122 +123+ |
+
+ # File 'lib/rspec/rails/example/controller_example_group.rb', line 119 +def routes + before do + self.routes = yield + end +end+ |
+
Container module for routing spec functionality.
+Default host to be used in Rails route helpers if none is specified.
+"www.example.com"
Shim to check for presence of Capybara.
+Shim to check for presence of Capybara. Will delegate if present, raise
+if not. We assume here that in most cases visit
will be the first
+Capybara method called in a spec.
+ +27 +28 +29 +30 +31 +32 +33+ |
+
+ # File 'lib/rspec/rails/example/feature_example_group.rb', line 27 +def visit(*) + if defined?(super) + super + else + raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\"" + end +end+ |
+
Container module for helper specs.
+Returns an instance of ActionView::Base with the helper being specified mixed in, along with any of the built-in rails helpers.
+Returns an instance of ActionView::Base with the helper being specified +mixed in, along with any of the built-in rails helpers.
+
+ +22 +23 +24 +25 +26 +27+ |
+
+ # File 'lib/rspec/rails/example/helper_example_group.rb', line 22 +def helper + _view.tap do |v| + v.extend(ApplicationHelper) if defined?(ApplicationHelper) + v.assign(view_assigns) + end +end+ |
+
Container module for job spec functionality.
+Container module for mailbox spec functionality.
+Passes if the inbound email was delivered.
+Passes if the inbound email bounced during processing.
+Passes if the inbound email failed to process.
+Process an inbound email message directly, bypassing routing.
+Passes if the inbound email was delivered
+
+ +44 +45 +46+ |
+
+ # File 'lib/rspec/rails/example/mailbox_example_group.rb', line 44 +def have_been_delivered + satisfy('have been delivered', &:delivered?) +end+ |
+
Passes if the inbound email bounced during processing
+
+ +54 +55 +56+ |
+
+ # File 'lib/rspec/rails/example/mailbox_example_group.rb', line 54 +def have_bounced + satisfy('have bounced', &:bounced?) +end+ |
+
Passes if the inbound email failed to process
+
+ +64 +65 +66+ |
+
+ # File 'lib/rspec/rails/example/mailbox_example_group.rb', line 64 +def have_failed + satisfy('have failed', &:failed?) +end+ |
+
Process an inbound email message directly, bypassing routing.
+
+ +73 +74 +75 +76 +77+ |
+
+ # File 'lib/rspec/rails/example/mailbox_example_group.rb', line 73 +def process() + MailboxExampleGroup.create_inbound_email().tap do |mail| + self.class.mailbox_class.receive(mail) + end +end+ |
+
Container module for mailer spec functionality.
++ Modules: ClassMethods +
+Class-level DSL for mailer specs.
+Alias for described_class
.
Alias for described_class
.
+ +31 +32 +33+ |
+
+ # File 'lib/rspec/rails/example/mailer_example_group.rb', line 31 +def mailer_class + described_class +end+ |
+
Container module for Rails specific matchers.
++ Modules: ActionCable, ActionMailbox, ActiveJob, HaveHttpStatus, RedirectTo, RenderTemplate, RoutingMatchers + Classes: BaseMatcher, BeANew, SendEmail +
+Passes if actual is an instance of model_class
and returns true
for new_record?
.
Passes if actual returns true
for new_record?
.
Passes if the given model instance's valid?
method is true, meaning all of the ActiveModel::Validations
passed and no errors exist.
Passes if a job has been enqueued.
+Passes if a job has been performed.
+Passes if a message has been sent to a stream/object inside a block.
+Passes if a job has been enqueued inside block.
+Passes if an email has been enqueued inside block.
+Passes if response
has a matching HTTP status code.
Passes if a job has been performed inside block.
+Passes if the given inbound email would be routed to the subject inbox.
+Check email sending with specific parameters.
+Passes if actual is an instance of model_class
and returns true
for
+new_record?
. Typically used to specify instance variables assigned to
+views by controller actions
Use the with
method to specify the specific attributes to match on the
+new record.
+ +78 +79 +80+ |
+
+ # File 'lib/rspec/rails/matchers/be_a_new.rb', line 78 +def be_a_new(model_class) + BeANew.new(model_class) +end+ |
+
Passes if actual returns true
for new_record?
.
+ +25 +26 +27+ |
+
+ # File 'lib/rspec/rails/matchers/be_new_record.rb', line 25 +def be_new_record + BeANewRecord.new +end+ |
+
Passes if the given model instance's valid?
method is true, meaning
+all of the ActiveModel::Validations
passed and no errors exist. If a
+message is not given, a default message is shown listing each error.
+ +44 +45 +46+ |
+
+ # File 'lib/rspec/rails/matchers/be_valid.rb', line 44 +def be_valid(*args) + BeValid.new(*args) +end+ |
+
Passes if a job has been enqueued. May chain at_least, at_most or exactly to specify a number of times.
+
+ +436 +437 +438 +439+ |
+
+ # File 'lib/rspec/rails/matchers/active_job.rb', line 436 +def have_been_enqueued + check_active_job_adapter + ActiveJob::HaveBeenEnqueued.new +end+ |
+
Passes if a job has been performed. May chain at_least, at_most or exactly to specify a number of times.
+
+ +509 +510 +511 +512+ |
+
+ # File 'lib/rspec/rails/matchers/active_job.rb', line 509 +def have_been_performed + check_active_job_adapter + ActiveJob::HaveBeenPerformed.new +end+ |
+
Passes if a message has been sent to a stream/object inside a block.
+May chain at_least
, at_most
or exactly
to specify a number of times.
+To specify channel from which message has been broadcasted to object use from_channel
.
+ +50 +51 +52 +53 +54+ |
+
+ # File 'lib/rspec/rails/matchers/action_cable.rb', line 50 +def have_broadcasted_to(target = nil) + check_action_cable_adapter + ActionCable::HaveBroadcastedTo.new(target, channel: described_class) +end+ |
+
Passes if a job has been enqueued inside block. May chain at_least, at_most or exactly to specify a number of times.
+
+ +401 +402 +403 +404+ |
+
+ # File 'lib/rspec/rails/matchers/active_job.rb', line 401 +def have_enqueued_job(job = nil) + check_active_job_adapter + ActiveJob::HaveEnqueuedJob.new(job) +end+ |
+
Passes if an email has been enqueued inside block. +May chain with to specify expected arguments. +May chain at_least, at_most or exactly to specify a number of times. +May chain at to specify a send time. +May chain on_queue to specify a queue.
+
+ +250 +251 +252+ |
+
+ # File 'lib/rspec/rails/matchers/have_enqueued_mail.rb', line 250 +def have_enqueued_mail(mailer_class = nil, mail_method_name = nil) + HaveEnqueuedMail.new(mailer_class, mail_method_name) +end+ |
+
Passes if response
has a matching HTTP status code.
The following symbolic status codes are allowed:
+Rack::Utils::SYMBOL_TO_STATUS_CODE
ActionDispatch::TestResponse
aliases:
+:error
:missing
:redirect
:success
+ +374 +375 +376 +377 +378+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 374 +def have_http_status(target) + raise ArgumentError, "Invalid HTTP status: nil" unless target + HaveHttpStatus.matcher_for_status(target) +end+ |
+
Passes if a job has been performed inside block. May chain at_least, at_most or exactly to specify a number of times.
+
+ +476 +477 +478 +479+ |
+
+ # File 'lib/rspec/rails/matchers/active_job.rb', line 476 +def have_performed_job(job = nil) + check_active_job_adapter + ActiveJob::HavePerformedJob.new(job) +end+ |
+
Passes if the given inbound email would be routed to the subject inbox.
+
+ +68 +69 +70+ |
+
+ # File 'lib/rspec/rails/matchers/action_mailbox.rb', line 68 +def receive_inbound_email() + ActionMailbox::ReceiveInboundEmail.new() +end+ |
+
+ This module is part of a private API. + You should avoid using this module if possible, as it may be removed or be changed in the future. +
+Namespace for various implementations of ActionCable features
++ Classes: HaveStream +
++ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Provides the implementation for have_stream
, have_stream_for
, and have_stream_from
.
+Not intended to be instantiated directly.
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +31 +32 +33+ |
+
+ # File 'lib/rspec/rails/matchers/action_cable/have_streams.rb', line 31 +def does_not_match?(subscription) + !match(subscription) +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +11 +12 +13+ |
+
+ # File 'lib/rspec/rails/matchers/action_cable/have_streams.rb', line 11 +def + "expected to have #{}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +17 +18 +19+ |
+
+ # File 'lib/rspec/rails/matchers/action_cable/have_streams.rb', line 17 +def + "expected not to have #{}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +23 +24 +25 +26 +27+ |
+
+ # File 'lib/rspec/rails/matchers/action_cable/have_streams.rb', line 23 +def matches?(subscription) + raise(ArgumentError, "have_streams is used for negated expectations only") if no_expected? + match(subscription) +end+ |
+
+ This module is part of a private API. + You should avoid using this module if possible, as it may be removed or be changed in the future. +
+Namespace for various implementations of ActionMailbox features
++ This module is part of a private API. + You should avoid using this module if possible, as it may be removed or be changed in the future. +
+Namespace for various implementations of ActiveJob features
++ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Base class to build matchers. Should not be instantiated directly.
+BeANew, HaveHttpStatus::GenericStatus, HaveHttpStatus::NumericCode, HaveHttpStatus::SymbolicStatus, SendEmail
++ Modules: DefaultFailureMessages +
++ This constant is part of a private API. + You should avoid using this constant if possible, as it may be removed or be changed in the future. +
+Used to detect when no arg is passed to initialize
.
+nil
cannot be used because it's a valid value to pass.
Object.new.freeze
Generates a description using Matchers::EnglishPhrasing.
+Matchers are not diffable by default.
+A new instance of BaseMatcher.
+Used to wrap a block of code that will indicate failure by raising one of the named exceptions.
+Indicates if the match is successful.
+Most matchers are value matchers (i.e. meant to work with expect(value)
) rather than block matchers (i.e. meant to work with expect { }
), so this defaults to false.
#failure_message, #failure_message_when_negated
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a new instance of BaseMatcher.
+
+ +21 +22 +23+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 21 +def initialize(expected = UNDEFINED) + @expected = expected unless UNDEFINED.equal?(expected) +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Generates a description using Matchers::EnglishPhrasing.
+
+ +53 +54 +55 +56 +57+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 53 +def description + desc = RSpec::Matchers::EnglishPhrasing.split_words(self.class.matcher_name) + desc << RSpec::Matchers::EnglishPhrasing.list(@expected) if defined?(@expected) + desc +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Matchers are not diffable by default. Override this to make your +subclass diffable.
+
+ +62 +63 +64+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 62 +def diffable? + false +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +75 +76 +77+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 75 +def expects_call_stack_jump? + false +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Used to wrap a block of code that will indicate failure by +raising one of the named exceptions.
+This is used by rspec-rails for some of its matchers that +wrap rails' assertions.
+
+ +40 +41 +42 +43 +44 +45 +46 +47 +48+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 40 +def match_unless_raises(*exceptions) + exceptions.unshift Exception if exceptions.empty? + begin + yield + true + rescue *exceptions => @rescued_exception + false + end +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Indicates if the match is successful. Delegates to match
, which
+should be defined on a subclass. Takes care of consistently
+initializing the actual
attribute.
+ +29 +30 +31 +32+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 29 +def matches?(actual) + @actual = actual + match(expected, actual) +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Most matchers are value matchers (i.e. meant to work with expect(value)
)
+rather than block matchers (i.e. meant to work with expect { }
), so
+this defaults to false. Block matchers must override this to return true.
+ +70 +71 +72+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 70 +def supports_block_expectations? + false +end+ |
+
+ This module is part of a private API. + You should avoid using this module if possible, as it may be removed or be changed in the future. +
+Provides default implementations of failure messages, based on the description
.
Provides a good generic failure message.
+Provides a good generic negative failure message.
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Provides a good generic failure message. Based on description
.
+When subclassing, if you are not satisfied with this failure message
+you often only need to override description
.
+ +153 +154 +155+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 153 +def + "expected #{description_of @actual} to #{description}".dup +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Provides a good generic negative failure message. Based on description
.
+When subclassing, if you are not satisfied with this failure message
+you often only need to override description
.
+ +162 +163 +164+ |
+
+ # File 'lib/rspec/rails/matchers/base_matcher.rb', line 162 +def + "expected #{description_of @actual} not to #{description}".dup +end+ |
+
+ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Matcher class for be_a_new
. Should not be instantiated directly.
RSpec::Rails::Matchers::BaseMatcher::UNDEFINED
+#description, #diffable?, #expects_call_stack_jump?, #match_unless_raises, #supports_block_expectations?
+
+ +23 +24 +25 +26+ |
+
+ # File 'lib/rspec/rails/matchers/be_a_new.rb', line 23 +def with(expected_attributes) + attributes.merge!(expected_attributes) + self +end+ |
+
+ This module is part of a private API. + You should avoid using this module if possible, as it may be removed or be changed in the future. +
+Namespace for various implementations of have_http_status
.
+ Classes: GenericStatus, NumericCode, SymbolicStatus +
+Conversion function to coerce the provided object into an ActionDispatch::TestResponse
.
Instantiates an instance of the proper matcher based on the provided target
.
A formatted failure message if @invalid_response
is present, nil
otherwise.
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Conversion function to coerce the provided object into an
+ActionDispatch::TestResponse
.
+ +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 35 +def as_test_response(obj) + if ::ActionDispatch::Response === obj || ::Rack::MockResponse === obj + ::ActionDispatch::TestResponse.from_response(obj) + elsif ::ActionDispatch::TestResponse === obj + obj + elsif obj.respond_to?(:status_code) && obj.respond_to?(:response_headers) + # Acts As Capybara Session + # Hack to support `Capybara::Session` without having to load + # Capybara or catch `NameError`s for the undefined constants + obj = ActionDispatch::Response.new.tap do |resp| + resp.status = obj.status_code + resp.headers.clear + resp.headers.merge!(obj.response_headers) + resp.body = obj.body + resp.request = ActionDispatch::Request.new({}) + end + ::ActionDispatch::TestResponse.from_response(obj) + else + raise TypeError, "Invalid response type: #{obj}" + end +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Instantiates an instance of the proper matcher based on the provided
+target
.
+ +19 +20 +21 +22 +23 +24 +25 +26 +27+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 19 +def self.matcher_for_status(target) + if GenericStatus.valid_statuses.include?(target) + GenericStatus.new(target) + elsif Symbol === target + SymbolicStatus.new(target) + else + NumericCode.new(target) + end +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a formatted failure message if
+@invalid_response
is present, nil
otherwise.
+ +60 +61 +62 +63 +64 +65+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 60 +def + return unless @invalid_response + "expected a response object, but an instance of " \ + "#{@invalid_response.class} was received" +end+ |
+
+ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Provides an implementation for have_http_status
matching against
+ActionDispatch::TestResponse
http status category queries.
Not intended to be instantiated directly.
+Of status codes which represent a HTTP status code "group".
+Explaining why the match failed.
+Explaining why the match failed.
+A new instance of GenericStatus.
+true
if Rack's associated numeric HTTP code matched the response
code or the named response status.
as_test_response, #invalid_response_type_message, matcher_for_status
+#diffable?, #expects_call_stack_jump?, #match_unless_raises, #supports_block_expectations?
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a new instance of GenericStatus.
+
+ +251 +252 +253 +254 +255 +256 +257 +258 +259+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 251 +def initialize(type) + unless self.class.valid_statuses.include?(type) + raise ArgumentError, "Invalid generic HTTP status: #{type.inspect}" + end + @expected = type + @actual = nil + @invalid_response = nil +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns of status codes which represent a HTTP status +code "group".
+
+ +243 +244 +245 +246 +247 +248 +249+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 243 +def self.valid_statuses + [ + :error, :success, :missing, + :server_error, :successful, :not_found, + :redirect + ] +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +273 +274 +275+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 273 +def description + "respond with #{}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +278 +279 +280 +281+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 278 +def + || + "expected the response to have #{} but it was #{actual}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +284 +285 +286 +287+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 284 +def + || + "expected the response not to have #{} but it was #{actual}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns true
if Rack's associated numeric HTTP code matched
+the response
code or the named response status.
+ +263 +264 +265 +266 +267 +268 +269 +270+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 263 +def matches?(response) + test_response = as_test_response(response) + @actual = test_response.response_code + check_expected_status(test_response, expected) +rescue TypeError => _ignored + @invalid_response = response + false +end+ |
+
+ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Provides an implementation for have_http_status
matching against
+numeric http status codes.
Not intended to be instantiated directly.
+Explaining why the match failed.
+Explaining why the match failed.
+A new instance of NumericCode.
+true
if the numeric code matched the response
code.
as_test_response, #invalid_response_type_message, matcher_for_status
+#diffable?, #expects_call_stack_jump?, #match_unless_raises, #supports_block_expectations?
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a new instance of NumericCode.
+
+ +80 +81 +82 +83 +84+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 80 +def initialize(code) + @expected = code.to_i + @actual = nil + @invalid_response = nil +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +98 +99 +100+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 98 +def description + "respond with numeric status code #{expected}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +103 +104 +105 +106 +107+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 103 +def + || + "expected the response to have status code #{expected.inspect}" \ + " but it was #{actual.inspect}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +110 +111 +112 +113 +114+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 110 +def + || + "expected the response not to have status code " \ + "#{expected.inspect} but it did" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns true
if the numeric code matched the response
code.
+ +88 +89 +90 +91 +92 +93 +94 +95+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 88 +def matches?(response) + test_response = as_test_response(response) + @actual = test_response.response_code.to_i + expected == @actual +rescue TypeError => _ignored + @invalid_response = response + false +end+ |
+
+ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Provides an implementation for have_http_status
matching against
+Rack symbol http status codes.
Not intended to be instantiated directly.
+Explaining why the match failed.
+Explaining why the match failed.
+A new instance of SymbolicStatus.
+true
if Rack's associated numeric HTTP code matched the response
code.
as_test_response, #invalid_response_type_message, matcher_for_status
+#diffable?, #expects_call_stack_jump?, #match_unless_raises, #supports_block_expectations?
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a new instance of SymbolicStatus.
+
+ +131 +132 +133 +134 +135 +136+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 131 +def initialize(status) + @expected_status = status + @actual = nil + @invalid_response = nil + set_expected_code! +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +151 +152 +153+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 151 +def description + "respond with status code #{pp_expected}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +156 +157 +158 +159 +160+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 156 +def + || + "expected the response to have status code #{pp_expected} but it" \ + " was #{pp_actual}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns explaining why the match failed.
+
+ +163 +164 +165 +166 +167+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 163 +def + || + "expected the response not to have status code #{pp_expected} " \ + "but it did" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns true
if Rack's associated numeric HTTP code matched
+the response
code.
+ +141 +142 +143 +144 +145 +146 +147 +148+ |
+
+ # File 'lib/rspec/rails/matchers/have_http_status.rb', line 141 +def matches?(response) + test_response = as_test_response(response) + @actual = test_response.response_code + expected == @actual +rescue TypeError => _ignored + @invalid_response = response + false +end+ |
+
Matcher for redirects.
+Delegates to assert_redirected_to
.
Delegates to assert_redirected_to
.
+ +32 +33 +34+ |
+
+ # File 'lib/rspec/rails/matchers/redirect_to.rb', line 32 +def redirect_to(target) + RedirectTo.new(self, target) +end+ |
+
Matcher for template rendering.
+Delegates to assert_template
.
Delegates to assert_template
.
+ +56 +57 +58+ |
+
+ # File 'lib/rspec/rails/matchers/have_rendered.rb', line 56 +def have_rendered(, = nil) + RenderTemplateMatcher.new(self, , ) +end+ |
+
Matchers to help with specs for routing code.
++ Modules: RouteHelpers +
+Passes if the route expression is recognized by the Rails router based on the declarations in config/routes.rb
.
Delegates to assert_recognizes
.
Passes if the route expression is recognized by the Rails router based on
+the declarations in config/routes.rb
. Delegates to
+RouteSet#recognize_path
.
+ +101 +102 +103+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 101 +def be_routable + BeRoutableMatcher.new(self) +end+ |
+
Delegates to assert_recognizes
. Supports short-hand controller/action
+declarations (e.g. "controller#action"
).
+ +61 +62 +63+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 61 +def route_to(*expected) + RouteToMatcher.new(self, *expected) +end+ |
+
Helpers for matching different route types.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
Shorthand method for matching this type of route.
+
+ +116 +117 +118 +119 +120+ |
+
+ # File 'lib/rspec/rails/matchers/routing_matchers.rb', line 116 +%w[get post put patch delete options head].each do |method| + define_method method do |path| + { method.to_sym => path } + end +end+ |
+
+ This class is part of a private API. + You should avoid using this class if possible, as it may be removed or be changed in the future. +
+Matcher class for send_email
. Should not be instantiated directly.
+ This constant is part of a private API. + You should avoid using this constant if possible, as it may be removed or be changed in the future. +
+Define the email attributes that should be included in the inspection output.
+%i[subject from to cc bcc].freeze
A new instance of SendEmail.
+#description, #expects_call_stack_jump?, #match_unless_raises
++ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+Returns a new instance of SendEmail.
+
+ +16 +17 +18+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 16 +def initialize(criteria) + @criteria = criteria +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +38 +39 +40 +41 +42 +43 +44 +45 +46+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 38 +def + result = + if multiple_match? + "More than 1 matching emails were sent." + else + "No matching emails were sent." + end + "#{result}#{}" +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +50 +51 +52+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 50 +def + "Expected not to send an email but it was sent." +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +30 +31 +32 +33 +34+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 30 +def matches?(block) + define_matched_emails(block) + @matched_emails.one? +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +26 +27 +28+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 26 +def supports_block_expectations? + true +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +21 +22 +23+ |
+
+ # File 'lib/rspec/rails/matchers/send_email.rb', line 21 +def supports_value_expectations? + false +end+ |
+
Container class for model spec functionality. Does not provide anything +special over the common RailsExampleGroup currently.
+Common rails example functionality.
+Railtie to hook into Rails.
+Container class for request spec functionality.
+Delegates to Rails.application
.
Delegates to Rails.application
.
+ +16 +17 +18+ |
+
+ # File 'lib/rspec/rails/example/request_example_group.rb', line 16 +def app + ::Rails.application +end+ |
+
Container module for routing spec functionality.
++ Modules: ClassMethods +
+#delete, #get, #head, #options, #patch, #post, #put
++ This class handles dynamic methods through the method_missing method +
+
+ +56 +57 +58+ |
+
+ # File 'lib/rspec/rails/example/routing_example_group.rb', line 56 +def method_missing(m, *args, &block) + routes.url_helpers.respond_to?(m) ? routes.url_helpers.send(m, *args) : super +end+ |
+
Class-level DSL for route specs.
+Specifies the routeset that will be used for the example group.
+Specifies the routeset that will be used for the example group. This +is most useful when testing Rails engines.
+
+ +31 +32 +33 +34 +35+ |
+
+ # File 'lib/rspec/rails/example/routing_example_group.rb', line 31 +def routes + before do + self.routes = yield + end +end+ |
+
Container class for system tests
+Special characters to translate into underscores for #method_name
+['/', '.', ':', ',', "'", '"', " "].freeze
Default driver to assign if none specified.
+if ::Rails::VERSION::STRING.to_f >= 7.2 + :selenium_chrome_headless +else + :selenium +end
Delegates to Rails.application
.
for the SystemTesting Screenshot situation.
+Delegates to Rails.application
.
+ +94 +95 +96+ |
+
+ # File 'lib/rspec/rails/example/system_example_group.rb', line 94 +def app + ::Rails.application +end+ |
+
for the SystemTesting Screenshot situation
+
+ +29 +30 +31 +32 +33 +34 +35 +36 +37+ |
+
+ # File 'lib/rspec/rails/example/system_example_group.rb', line 29 +def passed? + return false if RSpec.current_example.exception + return true unless defined?(::RSpec::Expectations::FailureAggregator) + failure_notifier = ::RSpec::Support.failure_notifier + return true unless failure_notifier.is_a?(::RSpec::Expectations::FailureAggregator) + failure_notifier.failures.empty? && failure_notifier.other_errors.empty? +end+ |
+
Version information for RSpec Rails.
+Current version of RSpec Rails, in semantic versioning format.
+'7.1.0'
Helpers for making instance variables available to views.
+Assigns a value to an instance variable in the scope of the view being rendered.
+Compat-shim for AbstractController::Rendering#view_assigns.
+Assigns a value to an instance variable in the scope of the +view being rendered.
+
+ +11 +12 +13+ |
+
+ # File 'lib/rspec/rails/view_assigns.rb', line 11 +def assign(key, value) + _encapsulated_assigns[key] = value +end+ |
+
Compat-shim for AbstractController::Rendering#view_assigns
+
+ +16 +17 +18+ |
+
+ # File 'lib/rspec/rails/view_assigns.rb', line 16 +def view_assigns + super.merge(_encapsulated_assigns) +end+ |
+
Container class for view spec functionality.
++ Modules: ExampleMethods +
+DSL exposed to view specs.
+Provides access to the params hash that will be available within the view.
+Delegates to ActionView::Base#render, so see documentation on that for more info.
+Use rendered
instead.
Simulates the presence of a template on the file system by adding a Rails' FixtureResolver to the front of the view_paths list.
+Use view
instead.
The instance of ActionView::Base
that is used to render the template.
Provides access to the params hash that will be available within the +view.
+params[:foo] = 'bar'
+
+
+ +100 +101 +102+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 100 +def params + controller.params +end+ |
+
Delegates to ActionView::Base#render, so see documentation on that +for more info.
+The only addition is that you can call render with no arguments, and +RSpec will pass the top level description to render:
+describe "widgets/new.html.erb" do
+ it "shows all the widgets" do
+ render # => view.render(file: "widgets/new.html.erb")
+ # ...
+ end
+end
+
+
+ +66 +67 +68 +69 +70+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 66 +def render( = {}, local_assigns = {}, &block) + = if Hash === && .empty? + = .merge() if Hash === && .keys == [:locals] + super(, local_assigns, &block) +end+ |
+
Use rendered
instead.
+ +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 111 +def response + # `assert_template` expects `response` to implement a #body method + # like an `ActionDispatch::Response` does to force the view to + # render. For backwards compatibility, we use #response as an alias + # for #rendered, but it needs to implement #body to avoid + # `assert_template` raising a `NoMethodError`. + unless rendered.respond_to?(:body) + def rendered.body + self + end + end + rendered +end+ |
+
Simulates the presence of a template on the file system by adding a +Rails' FixtureResolver to the front of the view_paths list. Designed to +help isolate view examples from partials rendered by the view template +that is the subject of the example.
+stub_template("widgets/_widget.html.erb" => "This content.")
+
+
+ +92 +93 +94+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 92 +def stub_template(hash) + controller.prepend_view_path(StubResolverCache.resolver_for(hash)) +end+ |
+
Use view
instead.
+ +105 +106 +107 +108+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 105 +def template + RSpec.deprecate("template", replacement: "view") + view +end+ |
+
The instance of ActionView::Base
that is used to render the template.
+Use this to stub methods before calling render
.
describe "widgets/new.html.erb" do
+ it "shows all the widgets" do
+ view.stub(:foo) { "foo" }
+ render
+ # ...
+ end
+end
+
+
+ +82 +83 +84+ |
+
+ # File 'lib/rspec/rails/example/view_example_group.rb', line 82 +def view + _view +end+ |
+
Builds paths for view specs using a particular route set.
+A new instance of ViewPathBuilder.
+Given a hash of parameters, build a view path, if possible.
+Returns a new instance of ViewPathBuilder.
+
+ +5 +6 +7+ |
+
+ # File 'lib/rspec/rails/view_path_builder.rb', line 5 +def initialize(route_set) + self.class.send(:include, route_set.url_helpers) +end+ |
+
Given a hash of parameters, build a view path, if possible. +Returns nil if no path can be built from the given params.
+
+ +22 +23 +24 +25 +26+ |
+
+ # File 'lib/rspec/rails/view_path_builder.rb', line 22 +def path_for(path_params) + url_for(path_params.merge(only_path: true)) +rescue => e + e. +end+ |
+
Helpers for optionally rendering views in controller specs.
++ Modules: ClassMethods +
+Returns the controller object instance under test.
+Returns the controller object instance under test.
+
+ +12 +13 +14+ |
+
+ # File 'lib/rspec/rails/view_rendering.rb', line 12 +def controller + @controller +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +38 +39 +40+ |
+
+ # File 'lib/rspec/rails/view_rendering.rb', line 38 +def render_views? + self.class.render_views? || !controller.class.respond_to?(:view_paths) +end+ |
+
DSL methods
+
+ +21 +22 +23+ |
+
+ # File 'lib/rspec/rails/view_rendering.rb', line 21 +def render_views(true_or_false = true) + @render_views = true_or_false +end+ |
+
+ This method is part of a private API. + You should avoid using this method if possible, as it may be removed or be changed in the future. +
+
+ +26 +27 +28 +29 +30 +31 +32 +33 +34+ |
+
+ # File 'lib/rspec/rails/view_rendering.rb', line 26 +def render_views? + return @render_views if defined?(@render_views) + if superclass.respond_to?(:render_views?) + superclass.render_views? + else + RSpec.configuration.render_views? + end +end+ |
+
Adds methods (generally to ActionView::TestCase::TestController). +Intended for use in view specs.
+Adds methods extra_params=
and extra_params
to the indicated class.
Removes methods extra_params=
and extra_params
from the indicated class.
Adds methods extra_params=
and extra_params
to the indicated class.
+When class is ::ActionView::TestCase::TestController
, these methods
+are exposed in view specs on the controller
object.
+ +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45+ |
+
+ # File 'lib/rspec/rails/view_spec_methods.rb', line 11 +def add_to(klass) + return if klass.method_defined?(:extra_params) && klass.method_defined?(:extra_params=) + klass.module_exec do + # Set any extra parameters that rendering a URL for this view + # would require. + # + # @example + # + # # In "spec/views/widgets/show.html.erb_spec.rb": + # before do + # widget = Widget.create!(:name => "slicer") + # controller.extra_params = { :id => widget.id } + # end + def extra_params=(hash) + @extra_params = hash + request.path = + ViewPathBuilder.new(::Rails.application.routes).path_for( + extra_params.merge(request.path_parameters) + ) + end + # Use to read extra parameters that are set in the view spec. + # + # @example + # + # # After the before in the above example: + # controller.extra_params + # # => { :id => 4 } + def extra_params + @extra_params ||= {} + @extra_params.dup.freeze + end + end +end+ |
+
Removes methods extra_params=
and extra_params
from the indicated class.
+ +48 +49 +50 +51 +52 +53+ |
+
+ # File 'lib/rspec/rails/view_spec_methods.rb', line 48 +def remove_from(klass) + klass.module_exec do + undef extra_params= if klass.method_defined?(:extra_params=) + undef extra_params if klass.method_defined?(:extra_params) + end +end+ |
+
+
|
+
|
+
RSpec matcher | +Delegates to | +Available in | +Notes | +
---|---|---|---|
be_a_new |
++ | all | +primarily intended for controller specs | +
render_template |
+assert_template |
+request / controller / view | +use with expect(response).to |
+
redirect_to |
+assert_redirect |
+request / controller | +use with expect(response).to |
+
route_to |
+assert_recognizes |
+routing / controller | +use with expect(...).to route_to |
+
be_routable |
++ | routing / controller | +use with expect(...).not_to be_routable |
+
have_http_status |
++ | request / controller / feature | ++ |
match_array |
++ | all | +for comparing arrays of ActiveRecord objects | +
have_been_enqueued |
++ | all | +requires config: ActiveJob::Base.queue_adapter = :test |
+
have_enqueued_job |
++ | all | +requires config: ActiveJob::Base.queue_adapter = :test |
+
Follow the links above for examples of how each matcher is used.
+For a comprehensive look at RSpec Rails’ features, +read the official Cucumber documentation.
+RSpec Rails defines ten different types of specs
+for testing different parts of a typical Rails application.
+Each one inherits from one of Rails’ built-in TestCase
classes,
+meaning the helper methods provided by default in Rails tests
+are available in RSpec, as well.
Spec type | +Corresponding Rails test class | +
---|---|
model | ++ |
controller | +ActionController::TestCase |
+
mailer | +ActionMailer::TestCase |
+
job | ++ |
view | +ActionView::TestCase |
+
routing | ++ |
helper | +ActionView::TestCase |
+
request | +ActionDispatch::IntegrationTest |
+
feature | ++ |
system | +ActionDispatch::SystemTestCase |
+
Follow the links above to see examples of each spec type,
+or for official Rails API documentation on the given TestCase
class.
++Note: This is not a checklist.
+Ask a hundred developers how to test an application, +and you’ll get a hundred different answers.
+RSpec Rails provides thoughtfully selected features +to encourage good testing practices, but there’s no “right” way to do it. +Ultimately, it’s up to you to decide how your test suite will be composed.
+
When creating a spec file,
+assign it a type in the top-level describe
block, like so:
# spec/models/user_spec.rb
+RSpec.describe User, type: :model do
+...
+
+RSpec Rails provides some end-to-end (entire application) testing capability +to specify the interaction with the client.
+Also called acceptance tests, browser tests, or end-to-end tests, +system specs test the application from the perspective of a human client. +The test code walks through a user’s browser interactions,
+visit '/login'
fill_in 'Name', with: 'jdoe'
and the expectations revolve around page content.
+expect(page).to have_text('Welcome')
Because system specs are a wrapper around Rails’ built-in SystemTestCase
,
+they’re only available on Rails 5.1+.
+(Feature specs serve the same purpose, but without this dependency.)
Before Rails introduced system testing facilities, +feature specs were the only spec type for end-to-end testing. +While the RSpec team now officially recommends system specs instead, +feature specs are still fully supported, look basically identical, +and work on older versions of Rails.
+On the other hand, feature specs require non-trivial configuration +to get some important features working, +like JavaScript testing or making sure each test runs with a fresh DB state. +With system specs, this configuration is provided out-of-the-box.
+Like system specs, feature specs require the Capybara gem.
+Rails 5.1+ includes it by default as part of system tests,
+but if you don’t have the luxury of upgrading,
+be sure to add it to the :test
group of your Gemfile
first:
group :test do
+ gem "capybara"
+end
+
+Request specs are for testing the application +from the perspective of a machine client. +They begin with an HTTP request and end with the HTTP response, +so they’re faster than feature specs, +but do not examine your app’s UI or JavaScript.
+Request specs provide a high-level alternative to controller specs. +In fact, as of RSpec 3.5, both the Rails and RSpec teams +discourage directly testing controllers +in favor of functional tests like request specs.
+When writing them, try to answer the question, +“For a given HTTP request (verb + path + parameters), +what HTTP response should the application return?”
+Once you’ve cloned the repo and set up the environment, +you can run the specs and Cucumber features, or submit a pull request.
+rspec-rails
brings the RSpec testing framework to Ruby on Rails
+as a drop-in alternative to its default testing framework, Minitest.
In RSpec, tests are not just scripts that verify your application code. +They’re also specifications (or specs, for short): +detailed explanations of how the application is supposed to behave, +expressed in plain English.
+According to RSpec Rails new versioning strategy use:
+rspec-rails
7.x for Rails 7.x.rspec-rails
6.x for Rails 6.1, 7.0 or 7.1.rspec-rails
5.x for Rails 5.2 or 6.x.rspec-rails
4.x for Rails from 5.x or 6.x.rspec-rails
3.x for Rails earlier than 5.0.rspec-rails
1.x for Rails 2.x.IMPORTANT This README / branch refers to the 7.1.x stable release series, only bugfixes from this series will
+be added here. See the main
branch on Github if you want or
+require the latest unstable features.
rspec-rails
to both the :development
and :test
groups
+of your app’s Gemfile
: # Run against this stable release
+ group :development, :test do
+ gem 'rspec-rails', '~> 7.0.0'
+ end
+ # Or, run against the main branch
+ # (requires main-branch versions of all related RSpec libraries)
+ group :development, :test do
+ %w[rspec-core rspec-expectations rspec-mocks rspec-rails rspec-support].each do |lib|
+ gem lib, git: "https://github.com/rspec/#{lib}.git", branch: 'main'
+ end
+ end
+
+(Adding it to the :development
group is not strictly necessary,
+ but without it, generators and rake tasks must be preceded by RAILS_ENV=test
.)
# Download and install
+ $ bundle install
+ # Generate boilerplate configuration files
+ # (check the comments in each generated file for more information)
+ $ rails generate rspec:install
+ create .rspec
+ create spec
+ create spec/spec_helper.rb
+ create spec/rails_helper.rb
+
+If your project is already using an older version of rspec-rails
,
+upgrade to the latest version with:
$ bundle update rspec-rails
+
+RSpec follows semantic versioning,
+which means that “major version” upgrades (e.g., 2.x → 3.x)
+come with breaking changes.
+If you’re upgrading from version 2.x or below,
+read the rspec-rails
upgrade notes to find out what to watch out for.
Be sure to check the general RSpec upgrade notes as well.
+rails generate
# RSpec hooks into built-in generators
+$ rails generate model user
+ invoke active_record
+ create db/migrate/20181017040312_create_users.rb
+ create app/models/user.rb
+ invoke rspec
+ create spec/models/user_spec.rb
+# RSpec also provides its own spec file generators
+$ rails generate rspec:model user
+ create spec/models/user_spec.rb
+# List all RSpec generators
+$ rails generate --help | grep rspec
+
+# Default: Run all spec files (i.e., those matching spec/**/*_spec.rb)
+$ bundle exec rspec
+# Run all spec files in a single directory (recursively)
+$ bundle exec rspec spec/models
+# Run a single spec file
+$ bundle exec rspec spec/controllers/accounts_controller_spec.rb
+# Run a single example from a spec file (by line number)
+$ bundle exec rspec spec/controllers/accounts_controller_spec.rb:8
+# See all options for running specs
+$ bundle exec rspec --help
+
+Optional: If bundle exec rspec
is too verbose for you,
+you can generate a binstub at bin/rspec
and use that instead:
$ bundle binstubs rspec-core
+
+In RSpec, application behavior is described +first in (almost) plain English, then again in test code, like so:
+RSpec.describe 'Post' do #
+ context 'before publication' do # (almost) plain English
+ it 'cannot have comments' do #
+ expect { Post.create.comments.create! }.to raise_error(ActiveRecord::RecordInvalid) # test code
+ end
+ end
+end
+
+Running rspec
will execute this test code,
+and then use the plain-English descriptions
+to generate a report of where the application
+conforms to (or fails to meet) the spec:
$ rspec --format documentation spec/models/post_spec.rb
+Post
+ before publication
+ cannot have comments
+Failures:
+ 1) Post before publication cannot have comments
+ Failure/Error: expect { Post.create.comments.create! }.to raise_error(ActiveRecord::RecordInvalid)
+ expected ActiveRecord::RecordInvalid but nothing was raised
+ # ./spec/models/post.rb:4:in `block (3 levels) in <top (required)>'
+Finished in 0.00527 seconds (files took 0.29657 seconds to load)
+1 example, 1 failure
+Failed examples:
+rspec ./spec/models/post_spec.rb:3 # Post before publication cannot have comments
+
+For an in-depth look at the RSpec DSL, including lots of examples, +read the official Cucumber documentation for RSpec Core.
+In RSpec, assertions are called expectations,
+and every expectation is built around a matcher.
+When you expect(a).to eq(b)
, you’re using the eq
matcher.
In addition to the matchers that come standard in RSpec, +here are some extras that make it easier +to test the various parts of a Rails system:
+RSpec matcher | +Delegates to | +Available in | +Notes | +
---|---|---|---|
be_a_new |
++ | all | +primarily intended for controller specs | +
render_template |
+assert_template |
+request / controller / view | +use with expect(response).to |
+
redirect_to |
+assert_redirect |
+request / controller | +use with expect(response).to |
+
route_to |
+assert_recognizes |
+routing / controller | +use with expect(...).to route_to |
+
be_routable |
++ | routing / controller | +use with expect(...).not_to be_routable |
+
have_http_status |
++ | request / controller / feature | ++ |
match_array |
++ | all | +for comparing arrays of ActiveRecord objects | +
have_been_enqueued |
++ | all | +requires config: ActiveJob::Base.queue_adapter = :test |
+
have_enqueued_job |
++ | all | +requires config: ActiveJob::Base.queue_adapter = :test |
+
Follow the links above for examples of how each matcher is used.
+For a comprehensive look at RSpec Rails’ features, +read the official Cucumber documentation.
+RSpec Rails defines ten different types of specs
+for testing different parts of a typical Rails application.
+Each one inherits from one of Rails’ built-in TestCase
classes,
+meaning the helper methods provided by default in Rails tests
+are available in RSpec, as well.
Spec type | +Corresponding Rails test class | +
---|---|
model | ++ |
controller | +ActionController::TestCase |
+
mailer | +ActionMailer::TestCase |
+
job | ++ |
view | +ActionView::TestCase |
+
routing | ++ |
helper | +ActionView::TestCase |
+
request | +ActionDispatch::IntegrationTest |
+
feature | ++ |
system | +ActionDispatch::SystemTestCase |
+
Follow the links above to see examples of each spec type,
+or for official Rails API documentation on the given TestCase
class.
++Note: This is not a checklist.
+Ask a hundred developers how to test an application, +and you’ll get a hundred different answers.
+RSpec Rails provides thoughtfully selected features +to encourage good testing practices, but there’s no “right” way to do it. +Ultimately, it’s up to you to decide how your test suite will be composed.
+
When creating a spec file,
+assign it a type in the top-level describe
block, like so:
# spec/models/user_spec.rb
+RSpec.describe User, type: :model do
+...
+
+RSpec Rails provides some end-to-end (entire application) testing capability +to specify the interaction with the client.
+Also called acceptance tests, browser tests, or end-to-end tests, +system specs test the application from the perspective of a human client. +The test code walks through a user’s browser interactions,
+visit '/login'
fill_in 'Name', with: 'jdoe'
and the expectations revolve around page content.
+expect(page).to have_text('Welcome')
Because system specs are a wrapper around Rails’ built-in SystemTestCase
,
+they’re only available on Rails 5.1+.
+(Feature specs serve the same purpose, but without this dependency.)
Before Rails introduced system testing facilities, +feature specs were the only spec type for end-to-end testing. +While the RSpec team now officially recommends system specs instead, +feature specs are still fully supported, look basically identical, +and work on older versions of Rails.
+On the other hand, feature specs require non-trivial configuration +to get some important features working, +like JavaScript testing or making sure each test runs with a fresh DB state. +With system specs, this configuration is provided out-of-the-box.
+Like system specs, feature specs require the Capybara gem.
+Rails 5.1+ includes it by default as part of system tests,
+but if you don’t have the luxury of upgrading,
+be sure to add it to the :test
group of your Gemfile
first:
group :test do
+ gem "capybara"
+end
+
+Request specs are for testing the application +from the perspective of a machine client. +They begin with an HTTP request and end with the HTTP response, +so they’re faster than feature specs, +but do not examine your app’s UI or JavaScript.
+Request specs provide a high-level alternative to controller specs. +In fact, as of RSpec 3.5, both the Rails and RSpec teams +discourage directly testing controllers +in favor of functional tests like request specs.
+When writing them, try to answer the question, +“For a given HTTP request (verb + path + parameters), +what HTTP response should the application return?”
+Once you’ve cloned the repo and set up the environment, +you can run the specs and Cucumber features, or submit a pull request.
+t |