Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
Lee Avatar asked Sep 10 '09 17:09

Lee


2 Answers

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).

like image 80
Jerome Dalbert Avatar answered Sep 20 '22 15:09

Jerome Dalbert


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.

like image 36
Pete Hodgson Avatar answered Sep 21 '22 15:09

Pete Hodgson