【问题标题】:Pessimistic locking is not working properly with reload悲观锁定在重新加载时无法正常工作
【发布时间】:2018-10-02 23:15:52
【问题描述】:

悲观锁定在重新加载时无法正常工作(在测试用例中使用)。 with_lockreload 不能一起正常工作,测试用例会失败。如果我删除了with_lock,那么测试用例就可以正常工作。

def method_name1
  self.with_lock do
    attributes["amount_used"] = get_total_amount_used
    attributes["updated_at"] = Time.now.utc
    Product.where(:id => self.id).update_all(attributes)
  end
end

我使用 FactoryGirl 编写了单元测试用例。它调用method_name1,在使用量之后重新计算总数。如果您检查第一个测试用例 1:total = 600 和 amount_used = -200(-ve 表示减少),现在总计应该是 400.00。同样对于“测试用例 2”,运行“测试用例 1”后,总数为 400.00。 amount_used = 200(+ve 表示添加),总计应为 600.00。但是测试用例 2 说的是 800.00。

context 'description' do
  before(:each) do
    @product.total = 600
    @product.method_name1
  end

  it 'is updated automatically if valid' do
    @product.amount_used = -200
    @product.save
    @product.reload
    should eq('400.0')       #Working
  end

  it 'is not changed if invalid' do
    @product.amount_used = 200
    @product.save
    @product.reload
    should eq('600.0')      #Not Working
  end
end

测试用例 2 的错误: 失败/错误:应该 eq('600.0')

   expected: "600.0"
        got: "800.0"

   (compared using ==)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 locking factory-bot


    【解决方案1】:

    测试结果800为正确答案。

    before(:each) do
      @product.total = 600
      @product.method_name1
    end
    

    before(:each) 表示这段代码将在运行每个示例之前执行,因此 600 + 200 是 800。如果你希望它只运行一次,那么你必须使用 before(:all),那么这段代码将只运行一次在运行这两个示例之前。

    您可以在官方documentation 中查看更多信息。

    【讨论】:

    • 另外我想说你的测试顺序应该无关紧要。始终将测试构建为彼此独立。
    猜你喜欢
    • 2018-07-30
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多