【问题标题】:RSpec how to mock method inside another methodRSpec如何在另一个方法中模拟方法
【发布时间】:2019-11-08 15:16:19
【问题描述】:

application_controller 中,我有两种方法,我想在maintenance_mode_controller_specs 中进行测试。如何创建将返回 false 的模拟 maintenance_mode_active? 以在 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-rails ruby rspec


    【解决方案1】:

    maintenance_mode_active 是一个实例方法,您可以在类级别对它进行存根。你需要使用allow_any_instance_of

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

    【讨论】:

    • 因为 rubocop 我不能使用allow_any_instance_of,有没有其他选择?
    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多