mercredi 30 septembre 2015

Unit test rails associations with mocks

I have class that is responsible for doing some processing:

class Processor < ActiveRecord::Base
  def process
    # do some stuff
  end
end

and another class that is responsible for executing every processor and concatenating result. It's important to execute processors in correct order:

class ProcessorSet < ActiveRecord::Base
  has_many :processors, -> { order(:priority) }

  def process
    processors.map do |processor|
      processor.process
    end.join
  end      
end

How to test ProcessorSet.process method without having dependency with Processor (I don't want to test Process.process method, because it's already tested in another test unit). I've tried to mock processors method using mocha:

class ProcessorSetTest < ActiveSupport::TestCase
  processor_set = ProcessorSet.new

  processors = ['result1', 'result2'].map do |result|
    object = mock()
    object.expects(:process).returns(result)
    object
  end

  processor_set.expects(:processors).returns(processors)

  assert_equal 'result1result2', processor_set.process
end

But how in such case test that processors are returned in correct order?

Aucun commentaire:

Enregistrer un commentaire