Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert certain method is called with Ruby minitest framework?

I want to test whether a function invokes other functions properly with minitest Ruby, but I cannot find a proper assert to test from the doc.

The source code
class SomeClass   def invoke_function(name)     name == "right" ? right () : wrong ()   end    def right     #...   end    def wrong     #...   end end 
The test code:
describe SomeClass do   it "should invoke right function" do     # assert right() is called   end    it "should invoke other function" do     # assert wrong() is called   end end 
like image 461
steveyang Avatar asked Jun 03 '12 10:06

steveyang


People also ask

Does Minitest come with Ruby?

What is Minitest? 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.

What is mocking in Ruby on 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 .


1 Answers

Minitest has a special .expect :call for checking if some method is called.

describe SomeClass do   it "should invoke right function" do     mocked_method = MiniTest::Mock.new     mocked_method.expect :call, return_value, []     some_instance = SomeClass.new     some_instance.stub :right, mocked_method do       some_instance.invoke_function("right")     end     mocked_method.verify   end end 

Unfortunately this feature is not documented very well. I found about it from here: https://github.com/seattlerb/minitest/issues/216

like image 124
jvalanen Avatar answered Sep 29 '22 23:09

jvalanen