如何在Rspec中正确存根私有方法?

问题描述 投票:0回答:1

我尝试了很多次来解决此任务,但不能。我的应用程序控制器(before_filter)中有私有方法,我想以某种方式对其进行存根。这是此方法:

  def strip_invisible_chars
    Util::Strings.strip_control_chars(params)
  end

module Util
  class Strings
    def self.strip_control_chars(params)
      unsupported = [8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8203, 8204, 8205, 8238, 8239, 8206, 8207].map(&:chr).join

      if params.is_a?(Hash)
        params.each {|_, value| strip_control_chars(value)}
      elsif params.is_a?(String)
        params.delete!(unsupported)
      end
    end
  end
end   

这是我尝试进行存根处理,但没有结果。

describe '#strip_invisible_chars' do
    subject { controller.send :strip_invisible_chars }

    context 'when with params' do
      let(:params) { { one: 'two' } }

      before { allow(Util::Strings).to receive(:strip_control_chars).with(:params).and_return(true) }

      it 'returns result' do
        expect(subject).to be_truthy
      end
    end

    context 'when without params' do
      let(:params) {}

      before { allow(Util::Strings).to receive(:strip_control_chars).with({}).and_return(false) }

      it 'returns result' do
        expect(subject).to be_falsey
      end
    end
  end

块之前没有存根,所以我无法通过此测试。感谢任何帮助!

ruby rspec
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.