Created
May 11, 2020 18:24
-
-
Save kinnrot/7c9fe9c6c0fc45868d10b0adae22b04d to your computer and use it in GitHub Desktop.
Sample of mock leak between specs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
require "rspec/mocks/standalone" #spec/helpers.rb spec/helpers.rb:1 - without this line rspec prevents us from using mocks in context | |
class Box | |
attr_reader :color | |
def initialize | |
@color = Color.new | |
end | |
end | |
class Color | |
def name | |
:pink | |
end | |
end | |
describe Box do | |
subject { described_class.new } | |
context 'green box' do | |
before(:context) do | |
# Bad - will stay for all specs that executes after this one | |
allow_any_instance_of(Color).to receive(:name).and_return(:green) | |
end | |
describe 'color' do | |
it 'is green' do | |
color_name = subject.color.name | |
expect(color_name).to eq(:green) | |
end | |
end | |
end | |
context 'red box' do | |
around(:context) do |example| | |
# Better - This works, but no good reason to do it here. | |
RSpec::Mocks.with_temporary_scope do | |
allow_any_instance_of(Color).to receive(:name).and_return(:red) | |
example.run | |
# Mock clears itself, scope ends | |
end | |
end | |
describe 'color' do | |
it 'is red' do | |
color_name = subject.color.name | |
expect(color_name).to eq(:red) | |
end | |
end | |
end | |
end | |
describe Color do | |
subject(:color) { described_class.new } | |
describe '#name' do | |
it 'is pink' do | |
color_name = color.name | |
expect(color_name).to eq(:pink) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment