Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Mocking a class method with MiniTest?

Tags:

I'm using MiniTest 2.12.1 (the latest version of the stock testing framework shipped with Ruby >= 1.9) and I can't figure out how to mock a class method with it, the same way it's possible with the likes of Mocha, for example:

product = Product.new
Product.expects(:find).with(1).returns(product)
assert_equal product, Product.find(1)

I've been dabbling the Internet for days and I'm still to find a reasonable answer to this. Please help?

like image 913
Cristian R. Arroyo Avatar asked May 05 '12 19:05

Cristian R. Arroyo


People also ask

Is Minitest part of Ruby?

Minitest is a testing tool for Ruby that provides a complete suite of testing facilities. It also supports behaviour-driven development, mocking and benchmarking. With the release of Ruby 1.9, it was added to Ruby's standard library, which increased its popularity.

Does rails Minitest?

Minitest is the default testing suite used with Rails, so no further setup is required to get it to work.

What is mocking in rails?

Mocking is the practice of using fake objects to mimic the behaviour of real application components. Since mock objects simulate the behaviour of the original components, they can be used during testing of an isolated application code to handle its interaction with other parts of the application.


1 Answers

This might not be helpful to you if you're stuck using 2.12.1, but looks like they added method stubbing to minitest/mock in HEAD here.

So, were you to update to minitest HEAD, I think you could do this:

product = Product.new
Product.stub(:find, product) do
  assert_equal product, Product.find(1)
end
like image 182
Adam Avatar answered Sep 18 '22 13:09

Adam