RSpec: Applying stubs only within a block

When you mocked method calls in RSpec, they are mocked until the end of a spec, or until you explicitly release them.

You can use RSpec::Mocks.with_temporary_scope to have all mocks applied inside a block to be released when the block ends.
Example:

RSpec::Mocks.with_temporary_scope do
  allow(Rails).to receive(:env).and_return('production'.inquiry)
  puts Rails.env # prints "production"
end
puts Rails.env # prints "test"

Note that, when overriding pre-existing mocks inside the block, they are not reverted to the previously mocked behavior.
This is usually not relevant and you should be fine in most cases.

Arne Hartherz