rafaelss
rafaelss

Reputation: 81

Mock methods that receives a block as parameter

I have a scenario more or less like this

class A
  def initialize(&block)
    b = B.new(&block)
  end
end

I am unit testing class A and I want to know if B#new is receiving the block passed to A#new. I am using Mocha as mock framework.

Is it possible?

Upvotes: 7

Views: 2717

Answers (3)

Mark Maglana
Mark Maglana

Reputation: 604

Is B::new yielding to the block and does the block modify a param that yield provides? If yes, then you can test it this way:

require 'minitest/autorun'
require 'mocha/setup'

describe 'A' do

  describe '::new' do

    it 'passes the block to B' do
      params = {}
      block = lambda {|p| p[:key] = :value }
      B.expects(:new).yields(params)

      A.new(&block)

      params[:key].must_equal :value
    end

  end

end

Upvotes: 0

Bryan Ash
Bryan Ash

Reputation: 4479

I tried this with both Mocha and RSpec and although I could get a passing test, the behavior was incorrect. From my experiments, I conclude that verifying that a block is passed is not possible.

Question: Why do you want to pass a block as a parameter? What purpose will the block serve? When should it be called?

Maybe this is really the behavior you should be testing with something like:

class BlockParamTest < Test::Unit::TestCase

  def test_block_passed_during_initialization_works_like_a_champ
    l = lambda {|name| puts "Hello #{name}"}
    l.expects(:call).with("Bryan")
    A.new(&l) 
  end

end

Upvotes: 3

Bryan Ash
Bryan Ash

Reputation: 4479

I think you want:

l = lambda {}
B.expects(:new).with(l)
A.new(&l)

I know this works with RSpec, I'd be surprised if Mocha doesn't handle

Upvotes: 1

Related Questions