Clean up RSpec Global Namespace

Clean up RSpec Global Namespace

Today I learned (after reading this article) that in RSpec declared classes, modules, and structs are global. They pollute the global namespace and can cause order dependent spec failures. You can read up more on the topic here.

To avoid this you can this to your rails_helper.rb

RSpec.configure do |config|
  config.around(:example, remove_const: true) do |example|
    const_before = Object.constants

    example.run

    const_after = Object.constants
    (const_after - const_before).each do |const|
      Object.send(:remove_const, const)
    end
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Using SQL to find foreign key violations

Using SQL to find foreign key violations