简体   繁体   English

如何使用RSpec检测带有块的方法调用

[英]How to detect method calling with block using RSpec

I want to detect method calling with block using RSpec. 我想使用RSpec检测带有块的方法调用。

Deck#split_even_number is split numbers into even or odd. Deck#split_even_number是将数字分为偶数或奇数。 I want to detect Enumerable#partition is called with block. 我想检测Enumerable#partition是否被块调用。

I try using Proc.new { ... } , but this expectation is always failed. 我尝试使用Proc.new { ... } ,但是这种期望总是失败的。
I thins each Proc instance have different object id. 我使每个Proc实例具有不同的对象ID。

How to solve this..? 如何解决这个..?

class Deck
  def split_even_numbers
    @cards.partition { |card| card.even? }
  end
end

describe Deck do
  describe '#split_even_numbers' do
    let(:deck) { Deck.new(cards) }
    let(:cards) { [5, 4, 3, 2, 1] }


    # this test is more desirable than to detect method calling
    it do
      even, odd = deck.split_even_numbers

      aggregate_failures do
        expect(even).to match_array([2, 4])
        expect(odd).to match_array([1, 3, 5])
      end
    end

    it do
      expect(cards).to receive(:partition).with(no_args) do |&block|
        expect(block).to eq(Proc.new{ |card| card.even? })
      end
      deck.split_even_numbers
    end
  end
end

With the block form of receive you can get a handle on the proc that is passed. 使用receive的块形式,您可以获取传递的proc的句柄。 However, there is no way to really dig into the contents of the block. 但是,没有办法真正深入探讨该块的内容。 The only option is to make the proc publically accessible (a form of dependency injection): 唯一的选择是使proc可公开访问(一种依赖注入的形式):

class Deck
  ProcCallingEven = Proc.new(&:even?)
  def initialize(cards)
    @cards = cards
  end
  def split_even_numbers
    @cards.partition(&ProcCallingEven)
  end
end

describe Deck do
  describe '#split_even_numbers' do
    let(:cards) { [5, 4, 3, 2, 1] }
    let(:deck) { Deck.new(cards) }
    it do
      expect(cards).to receive(:partition) do |&block|
        expect(block).to be Deck::ProcCallingEven
      end
      deck.split_even_numbers
    end
  end
end

Although as already mentioned in comments To test something like this just makes sure that the code never changes. 尽管正如注释中已经提到的那样,要测试类似的东西,只需确保代码永不更改。 But code always changes just the result is supposed to be the same. 但是代码总是会改变,只是结果应该是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM