ruby-on-rails - RSpec如何在另一个方法中模拟方法
问题描述
在application_controller
我有两种方法,我想在maintenance_mode_controller_specs
. 如何创建maintenance_mode_active?
将返回false
以在内部使用它的模拟check_maintenance?
?
application_controller.rb
before_action :check_maintenance?
private
def check_maintenance?
if maintenance_mode_active? == true
redirect_to maintenance_mode
elsif request.fullpath.include?(maintenance_mode_path)
redirect_to :root
end
end
def maintenance_mode_active?
# do sth ...
mode.active?
end
maintenance_mode_controller_spec.rb
context 'when maintenance mode is active' do
let(:maintenance_mode?) { instance_double(ApplicationController) }
before do
allow(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
end
it 'redirect to root path' do
expect(described_class).should redirect_to(maintenance_mode_path)
end
end
解决方案
maintenance_mode_active
是一个实例方法,你在类级别上存根它。你需要使用allow_any_instance_of
before do
allow_any_instance_of(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
end
推荐阅读
- angularjs - 父 ng-repeat 中的搜索过滤器不起作用
- python - Cmd 不识别 pip 但 python shell 可以
- asp.net - 为什么具有两个参数的简单方法在 ASP.NET MVC 中不起作用?
- asp.net - ASP .Net MVC 应用程序
- java - 我的服务说它正在运行,但它的状态不清楚——它似乎没有被绑定
- java - Android从字符串包裹中设置图像
- java - 我应该保持数据库连接打开以处理每个请求吗?以及如何以正确的方式做到这一点
- c# - 将数据表分配为 tabitem.content 时获取 System.Data.DataRows 而不是实际值
- docker - 基于节点的 Docker 映像中缺少 Oracle 客户端库
- javascript - 在三元检查对象是否未定义之前,react 会为未定义的对象抛出类型错误