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

Rya*_*Mes 5 ruby rspec ruby-on-rails ruby-on-rails-4

我试图测试会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
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*uth 3

你可以这样做你所要求的事情:

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