Ruby:如何测试私有方法?

时间:2018-10-05 00:14:56

标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec-rails

我已为比赛条件实施了乐观锁。如果lock_version与数据库中更新的lock_version不匹配,则它将触发三次重试。您能否建议如何测试此重试事件。

注意:我无法更改私有方法2

公共

def method1
  begin
     method2
  rescue Exception => e

  end
end

私人

  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

测试用例:

  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

我在测试用例中遇到以下错误

 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

1 个答案:

答案 0 :(得分:4)

您已经在调用该方法之后设置期望值,这就是为什么您获得0次,在该行之后被调用0次的原因。

更改顺序,将期望值移到prod_v1.method1行上方,它将起作用。使用expect可用于私有和公共方法。