title: How to write optimistic locking test cases in Rails
body: <p>I need to test if my implementation of optimistic locking is correct or not. But I don't know how to test my functionalities. Here is the update action I wrote: </p>
  
  <pre><code>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
  </code></pre>
  
  <p>And here is the migration I added</p>
  
  <pre><code>class AddLockingColumnsToOperators &lt; ActiveRecord::Migration[5.1]
    def up
      add_column :operators, :lock_version, :integer, :default =&gt; 0, :null =&gt; false
    end
  
    def down
      remove_column :operators, :lock_version
    end
  end
  </code></pre>
  
  <p>Can anyone tell me how to test the update action above with rspec?</p>
  
  <p>Update: Here is the attempt I tried, but it didn't work</p>
  
  <pre><code>let!(:operator1) { FactoryBot.create(:operator, :site =&gt; site) }
  let!(:attributes) {
        {
          id: operator1.id,
          first_name: "test1",
          last_name: "test2",
          employee_number: "tesnt12345",
          badge: "test215235",
          suspended: true,
          site_id: site.id
        }
      }
      let!(:stale_attributes) {
        {
          id: operator1.id,
          first_name: "test_fake",
          last_name: "test_fake",
          employee_number: "tesnt12345",
          badge: "test215235",
          suspended: true,
          site_id: site.id
        }
      }
  
  it("cause StaleObjectError when updating same operator at the same time") do
          patch :update, params: { :id =&gt; operator1.id, :operator =&gt; attributes }
          patch :update, params: { :id =&gt; operator1.id, :operator =&gt; stale_attributes }
          expect(response).to raise_error(ActiveRecord::StaleObjectError)
        end
  </code></pre>