【问题标题】:Mocha: How to add expectation of a method when there are multiple invocations with different parametersMocha:当有多个不同参数的调用时如何添加对方法的期望
【发布时间】:2012-03-28 00:29:35
【问题描述】:

我有一个 Rails 控制器动作要测试。在那个动作中,一个方法 User.can?使用不同的参数多次调用。在其中一个测试用例中,我想确保调用 User.can?('withdraw') 。但我不关心 User.can 的调用?与其他参数。

def action_to_be_tested
  ...
  @user.can?('withdraw')
  ...
  @user.can?('deposit')
  ...
end

我在下面的测试中尝试过:

User.any_instance.expects(:can?).with('withdraw').at_least_once.returns(true)

但测试失败,消息表明意外调用 User.can?('deposit')。 如果我使用参数“存款”添加另一个期望,则测试通过。但我想知道是否有任何方法可以让我专注于使用 'withdraw' 参数的调用(因为其他调用与此测试用例无关)。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-mocha


    【解决方案1】:

    您可以将一个块传递给with 并让该块检查参数。使用它,您可以构建一个预期调用列表:

    invocations = ['withdraw', 'deposit']
    User.any_instance.expects(:can?).at_most(2).with do |permission|
      permission == invocations.shift
    end
    

    每次调用can?,Mocha 都会让步给区块。该块将从预期调用列表中提取下一个值,并根据实际调用对其进行检查。

    【讨论】:

    • 这应该是正确的答案,因为它完全符合我们的要求。
    • 无论如何,这对我不起作用。下面标记的答案虽然有效。
    【解决方案2】:

    我刚刚找到了一种解决方法,即使用不相关的参数将调用存根:

    User.any_instance.expects(:can?).with('withdraw').at_least_once.returns(true)
    User.any_instance.stubs(:can?).with(Not(equals('withdraw')))
    

    http://mocha.rubyforge.org/classes/Mocha/ParameterMatchers.html#M000023

    【讨论】:

    • 我知道the API 支持文字值(直接与变量比较),或者让步给块,但我不确定Not(...) 结构的来源。你能详细谈谈吗?
    • @Pysis Not() 来自与with() 一起使用的Mocha::ParameterMatchers。它们可以是 HasKey() 之类的骆驼壳或 has_key() 之类的蛇壳。 Not 必须是驼峰式大小写,因为它是关键字。
    【解决方案3】:

    @Innerpeacer 版本的更简单版本是:

    User.any_instance.stubs(:can?).with(any_parameters)
    User.any_instance.expects(:can?).with('withdraw')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多