jeudi 4 octobre 2018

Ruby: How to test private method?

I have implemented Optimistic Locking for Race Condition. If lock_version doesn't match with the updated lock_version in the database, then it will trigger retry three times. Can you suggest how to test this retry event.

Note: I can't change private method2

Public

def method1
  begin
     method2
  rescue Exception => e

  end
end

Private

  def method2
    tries = 0
    begin
      raise Product::StaleObjectError.new("Product is changed while you were editing") if stale_object?
      // Do some work
      raise Exception.new("Total amount used is greater than approved") if total_approved < 0

      // Save Product
    rescue Product::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        reload
        retry
      else
        raise Product::StaleObjectError("Product is changed while you were editing")
      end
    end
    attributes
  end

Test Case:

  it 'method1 should call three times if there is stale_object' do
    prod_v1 = Car.find(@car.id)
    prod_v1.stub(:stale_object?).and_return true
    prod_v1.method1
    expect{prod_v1}.to receive(:method2).exactly(3).times
  end

I am getting following error for test case

 Failure/Error: expect{car_v1}.to receive(:method2).exactly(3).times
   (#<Proc:).method2(any args)
       expected: 2 times with any arguments
       received: 0 times with any arguments

Aucun commentaire:

Enregistrer un commentaire