加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Mocha:我可以对带有参数的存根方法提出“永不

发布时间:2020-12-17 03:47:57 所属栏目:百科 来源:网络整理
导读:我的问题类似于这个问题: Mocha: stubbing method with specific parameter but not for other parameters obj.expects(:do_something).with(:apples).neverperform_action_on_obj perform_action_on_obj不会像我期望的那样调用do_something(:apples).但是
我的问题类似于这个问题: 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).如果是这样,我会收到意外的调用失败.

我的理解是,由于我从未将期望放在最后,它只适用于特定的修改期望.然而,似乎一旦我开始在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非常好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读