In this example I use rr gem, and stub an object method which is obj.project here, and assign returned value to any variable(in this case that is project_data ) when the method is called from any other method or class.
obj = Object.new
project_data = nil
stub(obj).project { |*x| project_data = x }
When I called any method that invokes project method with obj, project_data will be assigned by returned value of obj.project method. Is there any way to implement this technique with mocha gem? I googled the possible solutions but I couldn't figure out any solution
In mocha, with
allows you do specify a parameter matcher. You can pass a block to do an arbitrary test against the parameter(s) passed to the stubbed method.
The block should return true or false depending on whether the parameter is an acceptable value. In this example I'm always returning true
, since you haven't specified there is any restriction on the what is a valid parameter.
However the important bit is that since the block is executed whenever the stub is invoked, you can do the project_data
assignment there. Like this:
obj = Object.new
project_data = nil
obj.stubs(:project).with { |x| project_data = x; true }