Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub things in MiniTest?

Within my test I want to stub a canned response for any instance of a class.

It might look like something like:

Book.stubs(:title).any_instance().returns("War and Peace") 

Then whenever I call @book.title it returns "War and Peace".

Is there a way to do this within MiniTest? If yes, can you give me an example code snippet?

Or do I need something like mocha?

MiniTest does support Mocks but Mocks are overkill for what I need.

like image 532
Nick Avatar asked Aug 26 '11 22:08

Nick


People also ask

How do you stub a method in Minitest?

Stubbing in Minitest is done by calling . stub on the object/class that you want to stub a method on, with three arguments: the method name, the return value of the stub and a block. The block is basically the scope of the stub, or in other words, the stub will work only in the provided block.

What is a stub Ruby?

Stub. Definition of stub: A method stub is an instruction to an object (real or test double) to return a. known value in response to a message.

What is mocking in rails?

You use mocks to test the interaction between two objects. Instead of testing the output value, like in a regular expectation. For example: You're writing an API that flips images. Instead of writing your own image-manipulation code you use a gem like mini_magick .

Does rails Minitest?

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


2 Answers

  # Create a mock object   book = MiniTest::Mock.new   # Set the mock to expect :title, return "War and Piece"   # (note that unless we call book.verify, minitest will   # not check that :title was called)   book.expect :title, "War and Piece"    # Stub Book.new to return the mock object   # (only within the scope of the block)   Book.stub :new, book do     wp = Book.new # returns the mock object     wp.title      # => "War and Piece"   end 
like image 80
Panic Avatar answered Sep 19 '22 14:09

Panic


I use minitest for all my Gems testing, but do all my stubs with mocha, it might be possible to do all in minitest with Mocks(there is no stubs or anything else, but mocks are pretty powerful), but I find mocha does a great job, if it helps:

require 'mocha'     Books.any_instance.stubs(:title).returns("War and Peace") 
like image 30
daniel Avatar answered Sep 19 '22 14:09

daniel