Mocha:我可以对带有参数的存根方法提出"永不"的期望吗?

Bri*_*ian 4 testing unit-testing ruby-on-rails mocha.js ruby-on-rails-3

我的问题与此类似:Mocha:具有特定参数的存根方法,但不适用于其他参数

obj.expects(:do_something).with(:apples).never
perform_action_on_obj
Run Code Online (Sandbox Code Playgroud)

perform_action_on_obj不会叫do_something(:apples)我的期望.但是,它可能会打电话do_something(:bananas).如果是这样,我会收到意外的调用失败.

我的理解是,由于我放在never期望的最后,它只适用于特定的修改期望.然而,似乎一旦我开始嘲笑行为,obj我就从某种意义上"搞砸了".

如何允许其他do_something方法调用obj

编辑:这是一个明确的例子,完美地展示了我的问题:

describe 'mocha' do
  it 'drives me nuts' do
    a = mock()
    a.expects(:method_call).with(:apples)

    a.lol(:apples)
    a.lol(:bananas) # throws an unexpected invocation
  end 
end
Run Code Online (Sandbox Code Playgroud)

cha*_*eyc 8

以下是使用ParameterMatchers的解决方法:

require 'test/unit'
require 'mocha/setup'

class MyTest < Test::Unit::TestCase
  def test_something
    my_mock = mock()
    my_mock.expects(:blah).with(:apple).never
    my_mock.expects(:blah).with(Not equals :apple).at_least(0)
    my_mock.blah(:pear)
    my_mock.blah(:apple)
  end
end
Run Code Online (Sandbox Code Playgroud)

结果:

>> ruby mocha_test.rb 
Run options: 

# Running tests:

F

Finished tests in 0.000799s, 1251.6240 tests/s, 0.0000 assertions/s.

  1) Failure:
test_something(MyTest) [mocha_test.rb:10]:
unexpected invocation: #<Mock:0xca0e68>.blah(:apple)
unsatisfied expectations:
- expected never, invoked once: #<Mock:0xca0e68>.blah(:apple)
satisfied expectations:
- allowed any number of times, invoked once: #<Mock:0xca0e68>.blah(Not(:apple))


1 tests, 0 assertions, 1 failures, 0 errors, 0 skips
Run Code Online (Sandbox Code Playgroud)

一般来说,我同意你的观点:这种行为令人沮丧,并且违反了最不惊讶的原则.将上述技巧扩展到更一般的情况也很困难,因为你必须编写一个越来越复杂的"catchall"表达式.如果你想要更直观的东西,我发现RSpec的模拟效果非常好.