I notice that a lot of people prefer Mocha over RSpec's built in mocking framework. Can someone explain the advantages of Mocha, or any alternative, over RSpec's built in a mocking framework?
Ruby mocking frameworks have evolved a lot since this question has been asked in 2009. So here is a little 2013 comparison:
Expectations
expect(user).to receive(:say_hello)
user.expects(:say_hello).once
Stubbing an object
user = double(name: 'John Doe')
user = stub(name: 'John Doe')
Stubbing anything
User.any_instance.stub(:name).and_return('John Doe')
User.any_instance.stubs(:name).returns('John Doe')
They offer the same facilities, and both can be used with or without Rspec.
So I would say choosing one over another is a matter of personal taste (and they taste quite alike).
One specific feature I really like is being able to stub out all instances of a class. A lot of times I do something like the following with RSpec mocks:
stub_car = mock(Car) stub_car.stub!(:speed).and_return(100) Car.stub!(:new).and_return(stub_car)
with Mocha that becomes:
Car.any_instance.stubs(:speed).returns(100)
I find the Mocha version clearer and more explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With