2017-08-30 41 views
2

从Rails 4升级到Rails 5.1。运行rspec测试:Rails 5.1 - ActiveRecord :: RecordNotUnique.new错误的参数个数

Failure/Error: let(:exception) { 
ActiveRecord::RecordNotUnique.new("oops", Mysql2::Error) } 

ArgumentError: 
wrong number of arguments (given 2, expected 0..1) 

看来Rails 5中ActiveRecord异常的语法已经改变了吗?我不认为这是在任何'提到的Rails 5'新文章中提到的。谷歌发现没有,也没有源代码的网站。

回答

2

使用bundle open rails(假设使用bundler)在本地显示源代码。向上移动一个目录,你会在某个地方像~/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems(如果使用rbenv)。

搜索此目录将找到将解释的定义。使用议会和白银搜索器搜索例如:

:Ag 'class RecordNotUnique' ~/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems 

/Users/xxjjnn/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/errors.rb|98 col 3| class RecordNotUnique < WrappedDatabaseException 
/Users/xxjjnn/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.1.3/lib/active_record/errors.rb|109 col 3| class RecordNotUnique < WrappedDatabaseException 

,从这里我们可以看出,在Rails的5.1的方法现在不再需要两个参数:

# BOTH 
class RecordNotUnique < WrappedDatabaseException 
end 
class WrappedDatabaseException < StatementInvalid 
end 

# 4.2.7.1 
class StatementInvalid < ActiveRecordError 
    def initialize(message = nil, original_exception = nil) 
    if original_exception 
     ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \ 
             "Exceptions will automatically capture the original exception.", caller) 
    end 
    super(message || $!.try(:message)) 
    end 
    def original_exception 
    ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller) 
    cause 
    end 
end 
# 5.1.3 
class StatementInvalid < ActiveRecordError 
    def initialize(message = nil) 
    super(message || $!.try(:message)) 
    end 
end 

grepping源的这种技术可以解决许多像这样的问题。

相关问题