乐观的锁定单元测试Minitest

时间:2016-05-03 21:11:49

标签: ruby-on-rails ruby unit-testing minitest optimistic-locking

问题...... 尝试创建一个测试,证明乐观锁定阻止了保存但是保存操作实际上引发了ActiveRecord::StaleObjectError: Attempted to update a stale object: Invoice错误,从而炸毁了测试。如何更改测试的最后一行以正确表达?

  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  

我已经尝试过了......

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

但我收到了语法错误。

assert_not second.save "是的,它没有保存,因此没有机会在测试错误出现之前触发。"是的,它没有保存。"

1 个答案:

答案 0 :(得分:2)

当您要测试方法是否引发异常时,请使用assert_raises

要使用它,请传递一个包含您希望引发错误的方法的块,如下所示:

assert_raises(ExceptionClassYouExpect) { method_that_should_raise! }

在你的情况下,我认为这将是:

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

我总是参考Rails指南:http://guides.rubyonrails.org/testing.html#available-assertions