代码之家  ›  专栏  ›  技术社区  ›  doremi

rspec:如何只中止对同一方法的多个调用中的一个

  •  0
  • doremi  · 技术社区  · 6 年前

    我很难弄清楚如何只中止对一个方法的两个调用中的一个。下面是一个例子:

    class Example
      def self.foo
        { a: YAML.load_file('a.txt'),   # don't stub - let it load
          b: YAML.load_file('b.txt') }  # stub this one
      end
    end
    
    RSpec.describe Example do
      describe '.foo' do
        before do
          allow(YAML).to receive(:load_file).with('b.txt').and_return('b_data')
        end
    
        it 'returns correct hash' do
          expect(described_class.foo).to eq(a: 'a_data', b: 'b_data')
        end
      end
    end
    

    测试失败,因为我接到了一个电话 YAML.load_file 第二个调用的参数( 'b.txt' )不是它遇到的第一个( 'a.txt' )我原以为论点匹配可以解决这个问题,但事实并非如此。

    Failures:
    
      1) Example.foo returns correct hash
         Failure/Error:
           { a: YAML.load_file('a.txt'),
             b: YAML.load_file('b.txt') }
    
           Psych received :load_file with unexpected arguments
             expected: ("b.txt")
                  got: ("a.txt")
            Please stub a default value first if message might be received with other args as well.  
    

    我能让第一个电话 加载文件 去接但只接第二个电话?我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  1
  •   periswon    6 年前

    有一个 and_call_original 选项(见) rspec docs )

    应用到您的示例中,这应该满足您的需求:

    before do
      allow(YAML).to receive(:load_file).and_call_original
      allow(YAML).to receive(:load_file).with('b.txt').and_return('b_data')
    end