From e63a14277ec88c77b98d355b3a7fbc672339c65d Mon Sep 17 00:00:00 2001 From: Takumasa Ochi Date: Wed, 9 Mar 2022 17:12:21 +0900 Subject: [PATCH] Prevent unrelated exceptions by requiring `rails_helper` at `.rspec` When there is a bug in the code on the load, RSpec catches the exception, aborts the spec file, proceeds to the following spec file, and retries `require` with partially loaded Rails application. In some cases, we see many identical errors, such as `NameError`, which are noisy but help developers find the bug. In other cases, we see many unrelated errors, typically `FrozenError` on finalized objects, which push out the original exception raised only from the first spec. The following comment describes this issue in detail. https://github.com/thoughtbot/factory_bot_rails/issues/303#issuecomment-434560625 This patch prevents unrelated exceptions by the fail-fast feature. https://github.com/rspec/rspec-core/pull/2568 --- lib/generators/rspec/install/install_generator.rb | 9 +++++++++ spec/generators/rspec/install/install_generator_spec.rb | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/generators/rspec/install/install_generator.rb b/lib/generators/rspec/install/install_generator.rb index 8b832089d3..0f7cbb26a3 100644 --- a/lib/generators/rspec/install/install_generator.rb +++ b/lib/generators/rspec/install/install_generator.rb @@ -41,6 +41,9 @@ def generate_rspec_init(tmpdir) replace_generator_command(spec_helper_path) remove_warnings_configuration(spec_helper_path) + + dot_rspec_path = File.join(tmpdir, '.rspec') + prepend_require_rails_helper_option(dot_rspec_path) end def replace_generator_command(spec_helper_path) @@ -58,6 +61,12 @@ def remove_warnings_configuration(spec_helper_path) '', verbose: false end + + def prepend_require_rails_helper_option(dot_rspec_path) + prepend_to_file dot_rspec_path, + "--require rails_helper\n", + verbose: false + end end end end diff --git a/spec/generators/rspec/install/install_generator_spec.rb b/spec/generators/rspec/install/install_generator_spec.rb index fd16737f9b..0893cc4eec 100644 --- a/spec/generators/rspec/install/install_generator_spec.rb +++ b/spec/generators/rspec/install/install_generator_spec.rb @@ -47,11 +47,12 @@ def filter_rails_from_backtrace let(:rails_helper) { content_for('spec/rails_helper.rb') } let(:spec_helper) { content_for('spec/spec_helper.rb') } + let(:dot_rspec) { content_for('.rspec') } let(:developmentrb) { content_for('config/environments/development.rb') } it "generates .rspec" do run_generator - expect(file('.rspec')).to exist + expect(dot_rspec).to match(/\A--require rails_helper\n/) end it "generates spec/spec_helper.rb" do