RSpec attr_readonly

RSpec attr_readonly

我有一个产品具有名为 rfid

的只读属性
class Product < ActiveRecord::Base
  attr_readonly :rfid

我有以下规范来检查它是否确实是只读的

describe Product do
  before :each do
    @product = FactoryGirl.create(:product)
  end
  it "'s rfid is immutable'" do
    @product.update_attribute(:rfid, 1921)
    @product.valid?
    expect(@product.errors[:rfid]).to include("marked as readonly")
  end

但是它失败了 returns:

  1) Product 's rfid is immutable'
     Failure/Error: @product.update_attribute(:rfid, 1921)
     ActiveRecord::ActiveRecordError:
       rfid is marked as readonly

我试过 "has already been taken" expect(@product.rfid).to eq(1921)to have(1).errors 等无济于事

像往常一样,非常感谢任何帮助

尝试更新只读属性会引发 ActiveRecord::ActiveRecordError 错误,而不是向模型添加验证错误。您可以测试是否引发错误:

expect {
  @product.update_attribute(:rfid, 1921)
}.to raise_error(ActiveRecord::ActiveRecordError, 'rfid is marked as readonly')