ruby-on-rails - Mocha : Can I put a "never" expectation on a stubbed method WITH parameters?

标签 ruby-on-rails ruby-on-rails-3 unit-testing testing mocha.js

我的问题与此类似: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 上的行为,我就在某种意义上“搞砸了”。

如何允许对 objdo_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/

相关文章:

ruby-on-rails - 失败/错误:在 { visit signup_path } 之前 NameError:#<RSpec::Core::ExampleGroup 的未定义局部变量或方法 `signup_path'

ruby-on-rails - Rails db 不通过迁移添加新列

ruby-on-rails - 在 Windows 上运行 Ruby/Rails 的限制

java - 模拟 : mock method call with parameters by reflection

ruby-on-rails - Rails minitest 设计错误

java - JUnit - 用于测试单个类的文件有多少?

ruby-on-rails - 替换正则表达式中的每个模式

ruby-on-rails-3 - 是否可以通过 RSpec/Capybara 测试元素的顺序?

ruby-on-rails - 升级到 Rails 3.2.2 : How to solve the 'undefined method for Syck::DomainType' error related to the Delayed Job gem?

ruby-on-rails-3 - 如何使用mailman处理传入的邮件并将其更新到数据库中