升级到 Rails 4,现在出现"wrong number of arguments (1 for 2+)"错误



我最近将我的应用程序从Rails 3升级到Rails 4,我正在尝试运行规范测试。我认为曾经工作得很好的代码(在我在这里工作之前(突然抛出一个错误。

错误:

1) Admin::ReviewsController while logged in #index should get index
     Failure/Error: stub_search("product")
     ArgumentError:
       wrong number of arguments (1 for 2+)
     # ./spec/support/searchkick_stub.rb:5:in `stub_search'
     # ./spec/controllers/admin/reviews_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

这是searchkick_stub.rb:

module SearchkickStub
  def stub_search(model)
    klass = model.to_s.camelize.constantize
    klass.any_instance.stub(:reindex) { true }
    klass.stub(:search) do |term, options|
      options ||= {}
      @search_term ||= term
      @search_params ||= options.dup
      response = {
    'hits' => {
          'total' => 0,
          'hits' => [],
    }
      }
      result_opts = {
    # per Searchkick::Query.new
    page: [options[:page].to_i, 1].max,
    per_page: (options[:limit] || options[:per_page] || 100000).to_i,
    padding: [options[:padding].to_i, 0].max,
    load: options[:load].nil? ? true : options[:load],
    # per Searchkick::Query.execute
    includes: options[:include] || options[:includes],
    json: !options[:json].nil?,
      }
      Searchkick::Results.new(klass, response, result_opts)
    end
    # Code that reindexes Products will reindex their Inventories too.
    stub_search(:inventory) if model == :product
  end
end

stub_search的签名显然是针对单个参数的,而不是像错误声明那样的两个或多个参数。

这是我们在 reviews_controller_spec.rb 中使用 stub_search 的地方

describe ReviewsController do
  include SearchkickStub
  before do
    stub_search(:product)
    ...
  end
end

通了。根据 https://github.com/rspec/rspec-rails/issues/941,问题是行:require 'minitest/autorun' spec_helper.rb。添加此行是为了删除以下警告:

Warning: you should require 'minitest/autorun' instead.
Warning: or add 'gem "minitest"' before 'require "minitest/autorun"'

但事实证明,您所需要的只是在 Gemfile 中gem "minitest"(即使它已经安装,作为其他内容的依赖项,并出现在 Gemfile.lock 中(。

我认为问题更多地来自红宝石升级。解释器可能已经围绕如何处理块参数进行了更改。搜索方法被存根以在代码中采用 2 个参数:termoptions 。但它只被一个参数调用:"product" .

options 设置为该块中第一行的默认值,options ||= {}因此不传递选项可能不是 1.9.3 的问题,但通过更严格的参数检查,它会在 2.1.5 中中断。


一个简单的解决方法是在块参数中设置默认参数,例如。

klass.stub(:search) do |term, options|

klass.stub(:search) do |term, options={}|

执行此操作后,您还可以安全地删除options ||= {}行。

相关内容

最新更新