mercredi 6 mai 2015

How can I mock with a block in minitest?

Hopefully a simple question for MiniTest folks..

I have a section of code which I'll condense into an example here:

class Foo
  def initialize(name)
    @sqs    = Aws::SQS::Client.new
    @id     = @sqs.create_queue( queue_name: name ).fetch(:queue_url)
    @poller = Aws::SQS::QueuePoller.new(@id)
  end
  def pick_first
    @poller.poll(idle_timeout: 60) do |message|
      process_msg(message) if some_condition(message)
    end
  end

How can I mock/stub/something-else so that I can feed a message through to be tested by the some_condition() and possibly processed with process_msg()?

I.e. I want to test the @poller.poll(idle_timeout: 60) do |message|.

I have tried to stub the Aws::SQS::QueuePoller#new with a mock poller, but it's not yielding the message to |message| just returning it..

This is what I have, which is not working:

mockqueue = MiniTest::Mock.new

mocksqs = MiniTest::Mock.new
mocksqs.expect :create_queue, mockqueue, [Hash]

mockpoller = MiniTest::Mock.new                                                                                                                         
mockpoller.expect :poll, 'message', [{ idle_timeout: 60 }]

Aws::SQS::Client.stub :new, mocksqs do
  Aws::SQS::QueuePoller.stub :new, mockpoller do
    queue = Foo.new(opts)
    queue.pick_first
  end
end

If I receive a variable in #pick_first, that's where the mock puts it, not into |message|:

def pick_first
    receiver = @poller.poll(idle_timeout: 60) do |message|
      process_msg(message) if some_condition(message)
    end
    puts receiver # this shows my 'message' !!! WHYYYY??
  end

Aucun commentaire:

Enregistrer un commentaire