mercredi 3 octobre 2018

RSpec: How to raise the exception in private method

I have implemented Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product. Method: recalculate is calling private method_1 then it saves (save!) the product. I can't use save! in private method_1, because it will fail the other things. I don't want to restructure the business logic.

#Product: Model's new field:
    #  lock_version                       :integer(4)      default(0), not null

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(car_v2).to receive(:method1).and_raise(ActiveRecord::StaleObjectError)
  end

When I try to write above the test case, then it should raise an Exception ActiveRecord::StaleObjectError. However, I am getting an error like

 Failure/Error: expect(car_v2).to receive(:set_total_and_buckets_used).and_raise(ActiveRecord::StaleObjectError)
 ArgumentError:
   wrong number of arguments (0 for 2)

Aucun commentaire:

Enregistrer un commentaire