我有一个 Rails Controller Action 要测试。在那个 Action 中,一个方法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”参数的调用(因为其他调用与此测试用例无关)。
最佳答案
您可以将 block 传递给 with 并让该 block 检查参数。使用它,您可以构建预期调用列表:
invocations = ['withdraw', 'deposit']
User.any_instance.expects(:can?).at_most(2).with do |permission|
permission == invocations.shift
end
每次调用 can? 时,Mocha 都会屈服于该 block 。该 block 将从预期调用列表中提取下一个值,并根据实际调用检查它。
关于ruby-on-rails - 摩卡 : How to add expectation of a method when there are multiple invocations with different parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899578/