Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test that an enum action method validates the object before creation or saving?

I am trying to test that Lead.new(params).active! raises an error. What is the best way to go about this?

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

I know I can set the enum value manually and then test valid? on the object that I instantiate, but I was hoping there was a way to test stale! and converted! which save to the database when called.

like image 821
Ryan-Neal Mes Avatar asked Nov 01 '22 02:11

Ryan-Neal Mes


1 Answers

You can do what you're asking this way:

expect { Lead.new.stale! }.to raise_error(
  ActiveRecord::RecordInvalid, "Validation failed: Value invalid for new leads")
like image 54
Dave Schweisguth Avatar answered Nov 09 '22 09:11

Dave Schweisguth