Ruby on rails 如何在创建或保存对象之前测试枚举操作方法是否验证对象?

Ruby on rails 如何在创建或保存对象之前测试枚举操作方法是否验证对象?,ruby-on-rails,ruby,ruby-on-rails-4,rspec,Ruby On Rails,Ruby,Ruby On Rails 4,Rspec,我正在尝试测试Lead.new(params.active)引发错误。最好的办法是什么 class Lead < ActiveRecord::Base enum status: { stale: 0, active: 1, converted: 2 } validate :existing_lead, on: :create private def existing_lead if new_record? && (stale? || conv

我正在尝试测试
Lead.new(params.active)引发错误。最好的办法是什么

class Lead < ActiveRecord::Base
  enum status: { stale: 0, active: 1, converted: 2 }

  validate  :existing_lead, on: :create

  private

  def existing_lead
    if new_record? && (stale? || converted?)
      errors.add(:status, "invalid for new leads") 
    end
  end
end
class Lead

我知道我可以手动设置枚举值,然后在实例化的对象上测试
valid?
,但我希望有一种方法可以测试
stale
已转换调用时将其保存到数据库。

您可以通过以下方式执行所需操作:

expect { Lead.new.stale! }.to raise_error(
  ActiveRecord::RecordInvalid, "Validation failed: Value invalid for new leads")

我想你的意思是你想测试
Lead.new.stale
Lead.new.converted引发错误,因为这些错误对新潜在客户无效。