ruby Minitest Mock#expect不接受第四个(关键字)参数

zwghvu4y  于 2023-05-28  发布在  Ruby
关注(0)|答案(1)|浏览(111)

我尝试使用Minitest模拟来验证对需要关键字参数的方法的调用;但是我得到了这个错误:

ArgumentError: wrong number of arguments (given 4, expected 2..3)

这是我的完整测试:

test ".toggle updates the category" do
    mock = Minitest::Mock.new
    mock.expect :update!, nil, [], {collapsed: true}
    CategoryAnalyzer.toggle_category(mock, true)
    mock.verify
  end

这是受试方法:

def self.toggle_category(category, collapsed)
    category.update!(collapsed: collapsed)
  end

我从minitest - mock - expect keyword arguments看到Minitest应该接受关键字参数。我的测试设置是否错误?我是否有一个旧版本的Minitest?(我的Gemfile.lock列出了minitest (5.18.0))我还应该检查什么?

3vpjnl9f

3vpjnl9f1#

  • https:rubyreferences.github.io/rubychanges/3.0.html#keyword-arguments-are-now-fully-separated-from-positional-arguments*

下面是使用4个参数调用expect的方法:

#           1         2    3   4
mock.expect :update!, nil, [], {collapsed: true}

这就是它所期望的:

#          1     2       3          keywords  block
def expect name, retval, args = [], **kwargs, &blk

因为 ruby v3.0{collapsed: true}是位置参数。要将其转换为关键字,您必须使用** splat或删除括号:

#           1         2    3   keywords
mock.expect :update!, nil, [], collapsed: true

# or this
mock.expect :update!, nil, [], **{collapsed: true}
kw = {collapsed: true}
mock.expect :update!, nil, [], **kw

一个简单的演示:

def arg_or_kwarg(one = nil, two = nil, **kwargs)
  {one: one, two: two, kwargs: kwargs}
end

# pass argument #1
>> arg_or_kwarg({hash: :arg})
=> {:one=>{:hash=>:arg}, :two=>nil, :kwargs=>{}}

# pass keyword argument
>> arg_or_kwarg(kw: :arg)
=> {:one=>nil, :two=>nil, :kwargs=>{:kw=>:arg}}

相关问题