我的问题与此类似:Mocha: stubbing method with specific parameter but not for other parameters
obj.expects(:do_something).with(:apples).never
perform_action_on_obj
perform_action_on_obj
不会像我预期的那样调用 do_something(:apples)
。但是,它可能会调用 do_something(:bananas)
。如果是这样,我会遇到意外的调用失败。
我的理解是,由于我将 never
放在期望的末尾,它只适用于特定修改后的期望。然而,一旦我开始模拟 obj
上的行为,我就在某种意义上“搞砸了”。
如何允许对 obj
的 do_something
方法进行其他调用?
编辑:这是一个清晰的例子,完美地展示了我的问题:
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
最佳答案
这是使用 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
结果:
>> 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
总的来说,我同意你的看法:这种行为令人沮丧,并且违反了最少惊奇原则。也很难将上面的技巧扩展到更一般的情况,因为您将不得不编写一个越来越复杂的“catchall”表达式。如果您想要更直观的东西,我会找到 RSpec's mocks非常好。
关于ruby-on-rails - Mocha : Can I put a "never" expectation on a stubbed method WITH parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287665/