【问题标题】:RSpec - Mock ampersand-symbol parametersRSpec - 模拟 & 符号参数
【发布时间】:2012-03-22 13:20:34
【问题描述】:

我有以下代码

def foo(bar)
  bar.map(&:to_sym)
end

我想将期望设置为map&:to_sym。如果我这样做了

describe '#foo' do
  it 'should convert to array of symbols' do
    bar = %w(test1 test2)
    bar.should_receive(:map).with(&:to_sym)
    foo(bar)
  end
end

它失败了

ArgumentError: no receiver given

有什么想法可以做到这一点吗?

【问题讨论】:

    标签: ruby rspec mocking


    【解决方案1】:

    好的,我现在更了解发生了什么。 这段代码不仅仅只是将一个对象发送到一个方法。

    bar.map(&:to_sym)
    

    “map 方法,从“混合”到 Array 类的 Enumerable 模块,为 self 的每个元素(在本例中为数组)调用一次块参数,并返回一个包含由返回的值的新数组块。但是在这种情况下,我们没有块,我们有 &:capitalize .....当一元 & 符号附加到 Ruby 中的对象时,如果对象不是 Proc 对象,解释器会尝试通过调用 to_proc 将对象转换为 proc。由于 :capitalize 是 Symbol,而不是 Proc,Ruby 继续发送 to_proc 消息到 :capitalize,.." http://swaggadocio.com/post/287689063

    http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html

    基本上,您正在尝试验证一个块是否正在传递到#map,我不相信您可以在 rspec 中做到这一点。基本上是这样的:

        bar.map {|element| element.to_sym}
    

    我还要说,这个测试很大程度上依赖于 #foo 的实现细节,这往往会使测试变得脆弱,因为方法内的代码在重构中发生变化是很常见的。相反,您应该测试该方法是否返回了正确的值。

        describe '#foo' do
          it 'should convert to array of symbols' do
            bar = %w(test1 test2)
            foo(bar).should == [:test1 , :test2]
          end
        end
    

    【讨论】:

    • 谢谢,它帮助我找到了最好的解决方案!
    【解决方案2】:

    #foo 方法需要一个您没有提供的参数

    describe '#foo' do
      it 'should convert to array of symbols' do
        bar = %w(test1 test2)
        bar.should_receive(:map).with(&:to_sym)
        foo(bar) #change your original line to this
      end
    end
    

    【讨论】:

    • 是的,这是一个错字。但是,它并没有回答问题。
    【解决方案3】:

    感谢大家的提问。最后,我来到了下面的代码。它不会对#map 设定期望,但会确保数组的每个元素都转换为符号:

    def foo(bar)
      bar.map(&:to_sym)
    end
    
    describe '#foo' do
      it 'should convert to array of symbols' do
        bar = %w(test1 test2)
        bar.each do |i|
          sym = i.to_sym
          i.should_receive(:to_sym).and_return(sym)
        end
        foo(bar)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多