Why are class instance variables persisting across specs?

2768 views ruby
5

I'm using class instance variables to keep track of @instances. When I run each spec individually, they pass. But when I run all of the together, there is unexpected behavior.

it "returns 1" do
  mock = Mock.new
  expect(Mock.count).to eq(1)
end

it "returns 2" do
  mock = Mock.new
  mock = Mock.new
  expect(Mock.count).to eq(2)
end

When I run either individually, all specs are green. But when I run both, the second spec returns a count of 3. So I see that Mock is somehow persisting across specs. I'm using plain ruby, no DB or rails or anything.

answered question

2 Answers

9

That's what class instance variables do. They are state of the class itself, which normally persists through the lifetime of the app (or test suite run, in your case).

posted this
13

I'm not sure if this might help you but you can try putting in test.rb:

Rails.application.configure do
  config.cache_classes = false
end

Clear your rails cache so the classes are not reused in different mocks. I didn't have time to test it but maybe it works. Consider that this is not very performant.

posted this

Have an answer?

JD

Please login first before posting an answer.