I have some code like this:
new_method = lambda do
puts "Hey, I'm the new method!"
redirect_to login_path
end
MyController.any_instance.stubs(:my_method).returns(new_method)
The problem is it's returning the lambda, instead of calling it...
So how do I stub controller methods? Or to put it differently, how do I stub a method and return a block to be run?
I had no luck with mocha
, but minitest/mock
does run lambda blocks, but only for class methods:
require 'minitest/mock'
new_thing = lambda do
puts "hi"
end
MyController.stub :my_class_method, new_thing do
MyController.my_class_method
end
To get instance methods stubbed, you can either get @controller
if you are in a controller test and stub that, or get another gem https://github.com/codeodor/minitest-stub_any_instance, which lets you do this:
new_thing = lambda do
puts "hi"
redirect_to login_path
end
MyController.stub_any_instance :my_method, new_thing do
visit my_controller_method_path
end