Mock methods that receives a block as parameter
Asked Answered
C

3

7

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?

Curtis answered 15/7, 2010 at 2:17 Comment(0)
A
3

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
Arborescent answered 16/7, 2010 at 2:31 Comment(0)
A
1

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

Arborescent answered 15/7, 2010 at 2:48 Comment(1)
Didn't work. I am starting to believe I cant do that in this way. I will try another approach here. Thanks! :)Curtis
H
0

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
Heinrich answered 2/12, 2014 at 0:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.