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?

Vega
  • 27,856
  • 27
  • 95
  • 103
rafaelss
  • 81
  • 1
  • 5

3 Answers3

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
Bryan Ash
  • 4,385
  • 3
  • 41
  • 57
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

Bryan Ash
  • 4,385
  • 3
  • 41
  • 57
  • Didn't work. I am starting to believe I cant do that in this way. I will try another approach here. Thanks! :) – rafaelss Jul 15 '10 at 17:08
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
Mark Maglana
  • 604
  • 7
  • 7