Skip to content

Commit

Permalink
Prevent unrelated exceptions by requiring rails_helper at .rspec
Browse files Browse the repository at this point in the history
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.
thoughtbot/factory_bot_rails#303 (comment)

This patch prevents unrelated exceptions by the fail-fast feature.
rspec/rspec-core#2568
  • Loading branch information
aeroastro committed Mar 9, 2022
1 parent b4f58f4 commit e63a142
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
9 changes: 9 additions & 0 deletions lib/generators/rspec/install/install_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
3 changes: 2 additions & 1 deletion spec/generators/rspec/install/install_generator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e63a142

Please sign in to comment.