What are the advantages of Mocha over RSpec's built in mocking framework? [closed] What are the advantages of Mocha over RSpec's built in mocking framework? [closed] ruby ruby

What are the advantages of Mocha over RSpec's built in mocking framework? [closed]


Ruby mocking frameworks have evolved a lot since this question has been asked in 2009. So here is a little 2013 comparison:

Expectations

  • with Rspec-mocks: expect(user).to receive(:say_hello)
  • with Mocha: user.expects(:say_hello).once

Stubbing an object

  • with Rspec-mocks: user = double(name: 'John Doe')
  • with Mocha: user = stub(name: 'John Doe')

Stubbing anything

  • with Rspec-mocks: User.any_instance.stub(:name).and_return('John Doe')
  • with Mocha: 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.


As far as I know Mocha supports Double Injections (aka Partial Mocking, which is also supported in rr), not sure that RSpec supports this feature too.

Also, for those who prefer to switch between testing frameworks, Mocha is a universal solution applicable for Test/Unit, Shoulda, etc. Using RSpec mocking with all these libs will be an overkill.