0

The Problem... Trying to create a test that demonstrates that optimistic locking prevents the save BUT the action of saving actually raises the ActiveRecord::StaleObjectError: Attempted to update a stale object: Invoice error, blowing up the test. How can I change the last line of the test to correctly express this?

  test "optimistic locking prevents save" do
    merchant = create(:merchant)
    invoice = Invoice.new(amount: 9.99,
                          currency: "USD",
                          item_count: 1,
                          invoice_id: build(:invoice).invoice_id,
                          merchant_id: merchant.merchant_id,
                          invoice_type: 'post-flight',
                          invoice_details_attributes: [
                          {
                            description: 'Detail1',
                            item_quantity: 1,
                            item_amount: 9.99,
                            detail_total: 9.99
                          }
                          ],
                          trips_attributes: [
                          {
                            passenger_first_name: 'Josh',
                            passenger_last_name: 'Smith',
                            depart_airport: 'MCI',
                            arrive_airport: 'SAN',
                            departure_date: 10.days.from_now,
                            passenger_count: 10
                          }
                          ])
    invoice.save!
    first  = Invoice.find(invoice.invoice_id)
    second = Invoice.find(invoice.invoice_id)
    first.currency  = "GBP"
    second.currency = "EUR"
    first.save
    second.save

    assert_equal ActiveRecord::StaleObjectError, Exception
  end  

I've tried...

rescue Exception => e
 puts $!.to_s
 assert_equal ActiveRecord::StaleObjectError, e
end

But I'm getting syntax errors.

assert_not second.save Doesn't get a chance to trigger as the tests errors out before it actually says "yes, it didn't save."

CheeseFry
  • 1,299
  • 1
  • 21
  • 38

1 Answers1

2

When you are looking to test whether a method raises an exception, use assert_raises.

To use it, pass a block containing the method you expect to raise an error, like so:

assert_raises(ExceptionClassYouExpect) { method_that_should_raise! }

In your case, I think this would be:

assert_raises(ActiveRecord::StaleObjectError) { second.save }

I always refer to the Rails Guides on this: http://guides.rubyonrails.org/testing.html#available-assertions.

Matt
  • 435
  • 3
  • 9