Ruby on rails 如何在Rails中编写乐观锁定测试用例

Ruby on rails 如何在Rails中编写乐观锁定测试用例,ruby-on-rails,rspec,optimistic-locking,Ruby On Rails,Rspec,Optimistic Locking,我需要测试乐观锁定的实现是否正确。但我不知道如何测试我的功能。以下是我编写的更新操作: def update begin @update_operator = Operator.find(params[:id]) authorize! :update, @update_operator if @update_operator.update_attributes(operator_params) render json: @update_

我需要测试乐观锁定的实现是否正确。但我不知道如何测试我的功能。以下是我编写的更新操作:

def update
    begin
      @update_operator = Operator.find(params[:id])
      authorize! :update, @update_operator
      if @update_operator.update_attributes(operator_params)
        render json: @update_operator, except: :badge
      else
        render json: @update_operator.errors, status: :unprocessable_entity
      end
    rescue ActiveRecord::StaleObjectError
      @update_operator.reload
      retry
    end
  end
这是我添加的迁移

class AddLockingColumnsToOperators < ActiveRecord::Migration[5.1]
  def up
    add_column :operators, :lock_version, :integer, :default => 0, :null => false
  end

  def down
    remove_column :operators, :lock_version
  end
end

您需要一个乐观锁定失败的测试用例

  • 首先获取您的编辑表单
  • 然后从独立更新更新记录
  • 然后提交编辑表单
  • 在功能测试中,它可能如下所示:

    visit "/operators/#{operator.id}/edit"
    
    indep_operator = Operator.find(operator.id)
    indep_operator.update!( ... some attributes ...)
    
    fill_in "Name", :with => "New Value"
    click_button "Update Operator"
    

    是的,我也试过类似的方法,但对我不起作用。您可以检查我的尝试,并告诉我是否需要更改任何内容在您的示例中,在更新部分,您没有获得锁定版本。您需要查询记录,获取锁定版本,然后有另一个更新,那么您的更新将过时。
    visit "/operators/#{operator.id}/edit"
    
    indep_operator = Operator.find(operator.id)
    indep_operator.update!( ... some attributes ...)
    
    fill_in "Name", :with => "New Value"
    click_button "Update Operator"