RSpec: Applying stubs only within a block

Posted . Visible to the public. Repeats.

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.

RSpec::Mocks.with_temporary_scope do
  allow(Rails).to receive(:env).and_return('production'.inquiry)
  puts Rails.env # prints "production"
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
Last edit
Arne Hartherz
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2024-07-03 15:36)