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:
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
And here is the migration I added
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
Can anyone tell me how to test the update action above with rspec?
Update: Here is the attempt I tried, but it didn't work
let!(:operator1) { FactoryBot.create(:operator, :site => 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 => operator1.id, :operator => attributes }
patch :update, params: { :id => operator1.id, :operator => stale_attributes }
expect(response).to raise_error(ActiveRecord::StaleObjectError)
end