You can achieve this by mocking new
method
class Service1
def foo
puts 'foo'
end
end
class Service2
def bar
3.times.each do
Service1.new().foo
end
end
end
Then the test:
let(:mocked_service) { instance_spy Service1 }
it "calls Service1.foo three times" do
allow(Service1).to receive(:new).and_return mocked_service
Service2.bar
expect(mocked_service).to have_received(:foo).exactly(3).times
end
However, as mentioned in the comment - the necessity of using mocks is a first sign of flawed OO design, meaning that the problem you posted is merely a symptom. Refer to SOLID principles to find better design.