首页 > 解决方案 > 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

标签: ruby-on-railsrubyrspec

解决方案


maintenance_mode_active是一个实例方法,你在类级别上存根它。你需要使用allow_any_instance_of

before do
  allow_any_instance_of(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
end

推荐阅读