更惯用的测试数据库条目已在 Rails 3 中修改的方法

More idiomatic way of testing that a database entry has been modified in Rails 3

在 Rails 3 中使用 RSpec 的以下集成测试中,我必须使用 new_product = Product.find(product) 来获取更改数据库内容的结果。这感觉有点单调。

有什么方法可以告诉 ActiveRecord 对象转到数据库并获取自对象创建以来发生的任何更改?

或者,是否有更自然的方式来指定数据库已针对此条目进行了修改?

require 'rails_helper'

describe 'admin' do
  it 'should edit a product' do
    original_product = create(:product)

    visit products_path
    # ASSUMPTION: Only one product on page.
    click_link 'Edit product'

    fill_in 'product_name', with: 'Foomaster 9000'
    fill_in 'product_price', with: '12.34'

    click_button('Save product')

    # REVIEW: Can the following line be improved?
    new_product = Product.find(original_product)

    # original_product still has old values for product_name and price
    expect(new_product.product_name).to eq('Foomaster 9000')
    expect(new_product.price).to eq(12_34)
  end
end

您可以使用 reload 方法通过主键查找重新加载对象。此重新加载发生在适当的位置,因此它将修改您的 original_product 变量。

original_product.reload
expect(original_product.name).to eq('Foomaster 9000')
expect(original_product.price).to eq(12_34)