Why are class instance variables persisting across specs?

2768 views ruby

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)

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

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


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

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

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?


Please login first before posting an answer.