Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a ActiveRecord::RecordInvalid for testing?

I have this piece of code that I am trying to test:

def error_from_exception(ex)
  if ex.is_a?(ActiveRecord::RecordInvalid)
...

To get into the if block, I need to pass in the correct ex param.

How do I create an ActiveRecord::RecordInvalid?

With rspec, I'm trying to do something like this:

context 'exception is ActiveRecord::RecordInvalid' do
  it 'returns the validation error' do
    begin
      raise ActiveRecord::RecordInvalid
    rescue Exception => ex
      binding.pry
      ###
      # From my pry session:
      # $ ex
      # $ <ArgumentError: wrong number of arguments (0 for 1)>
      # $ ex.class
      # $ ArgumentError < StandardError
      ###
    end


  end
end

How do I find out what argument type the library is looking for?

RecordInvalid link

like image 597
Eric Francis Avatar asked Sep 24 '14 18:09

Eric Francis


1 Answers

None of the above methods worked for me so I finally did the following while doing a spec:

class InvalidRecord
  include ActiveModel::Model
end


raise ActiveRecord::RecordInvalid.new(InvalidRecord.new)

Hope it helps!

like image 109
llekn Avatar answered Sep 17 '22 19:09

llekn