jeudi 4 octobre 2018

Rspec: How to test an exception which is getting raised in private method?

In my public method #recalculate, calling the private method1. This method throw exception 'ActiveRecord::StaleObjectError'.

def recalculate
  method_1
  self.save!
end

private
def method_1
    begin
      ####
      ####
      if self.lock_version == Product.find(self.id).lock_version
         Product.where(:id => self.id).update_all(attributes)
      else
         raise ActiveRecord::StaleObjectError.new(self, "test")
      end
    rescue ActiveRecord::StaleObjectError => e
        if tries < 3
           tries += 1
           sleep(1 + tries)
           self.reload
           retry
        else
           raise Exception.new(timeout.inspect)
        end
    end
end

Rspec Test case:

  it 'if car is updated then ActiveRecord::StaleObjectError should be raised' do
    prod_v1 =Product.find(@prod.id)
    prod_v2 = Car.find(@prod.id)
    prod_v1.recalculate
    prod_v1.reload  # will make lock_version of prod_v1 to 1

    prod_v2.recalculate # howvever lock_version of prod_v2 is still 0.

    expect(prod_v2.send(:method1)).to raise_error(ActiveRecord::StaleObjectError)

Error:

     Failure/Error: prod_v1.recalculate
 ActiveRecord::StaleObjectError:
   Attempted to Product is changed while you were editing a stale object: Product

Surprisingly, in error, it is showing Failure/Error: prod_v1.recalculate instead of Failure/Error: prod_v2.recalculate

Please suggest how to write the unit test case for an exception which is raised in private method. I have used send based on the link:

Aucun commentaire:

Enregistrer un commentaire