我正在尝试处理特定的ActiveRecord :: RecordInvalid异常并在不同异常时回退到默认值
rescue ActiveRecord::RecordInvalid => error
handle_specific_record_invalid_errors(error)
私人方法
def handle_specific_record_invalid_errors(error)
if error.record.errors.added?(:number, :taken)
fail MyCustonErrorClass
else
raise # This must re-raise the last exception, but fails rspec text, if I do (raise error) it works.
end
end
并在rspec测试中
let(:record) { build(:record) }
#this test works
it 'should raise Parsing::Errors::InvoiceAlreadySavedError' do
record.errors.add(:number, :taken)
exception = ActiveRecord::RecordInvalid.new(record)
expect do StoreParsedInvoice.new(some_data).send(:handle_specific_record_invalid_errors, exception)
end.to raise_error(MyCustomErrorClas)
end
#and this test fails with DRb::DRbConnError: druby://127.0.0.1:8989
it 'should raise ActiveRecord::RecordInvalid' do
record.errors.add(:number, :blank)
exception = ActiveRecord::RecordInvalid.new(record)
expect do
MyClass.new(some_data).send(:handle_specific_record_invalid_errors, exception)
end.to raise_error(ActiveRecord::RecordInvalid)
end
错误输出
Failure/Error: expect do
expected ActiveRecord::RecordInvalid, got #<DRb::DRbConnError: druby://127.0.0.1:8989 - #<Errno::ECONNREFUSED: Connection refused - connect(2) for "127.0.0.1" port 8989>> with backtrace:
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:744:in `rescue in block in open'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:738:in `block in open'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:737:in `each'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:737:in `open'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1248:in `initialize'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1228:in `new'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1228:in `open'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1141:in `block in method_missing'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1160:in `with_friend'
# /home/agm/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1140:in `method_missing'
答案 0 :(得分:0)
当你这样写:
rescue ActiveRecord::RecordInvalid => error
handle_specific_record_invalid_errors(error)
end
它实际上只会拯救例外ActiveRecord::RecordInvalid
并致电handle_specific_record_invalid_errors
,其他任何例外情况仍然会上升,而且它会转到handle_specific_record_invalid_errors
。