简体   繁体   中英

How to detect method calling with block using RSpec

I want to detect method calling with block using RSpec.

Deck#split_even_number is split numbers into even or odd. I want to detect Enumerable#partition is called with block.

I try using Proc.new { ... } , but this expectation is always failed.
I thins each Proc instance have different object 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. 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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