RSpec attr_readonly

时间:2015-02-12 23:13:41

标签: ruby-on-rails ruby activerecord rspec 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

但它失败并返回:

  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等无济于事

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

1 个答案:

答案 0 :(得分:1)

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

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