简体   繁体   English

Rails 中的存根控制器方法

[英]Stubbing controller methods in Rails

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...问题是它返回 lambda,而不是调用它......

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:我对mocha没有运气,但minitest/mock确实运行 lambda 块,但仅适用于类方法:

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:要获取实例方法存根,您可以在控制器测试中获取@controller并将其存根,或者获取另一个 gem https://github.com/codeodor/minitest-stub_any_instance ,它可以让您这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM