一起使用any_instance和should_receive是行不通的

时间:2013-11-28 16:26:41

标签: rspec mocking rspec-rails

简化我的问题:

  it 'should call resolve', focus: true do
    SubscriptionEventResolver.any_instance.should_receive(:resolve)
    SubscriptionEventResolver.new(double().as_null_object).resolve
  end

此测试失败,并显示以下消息:

Failures:

  1) SubscriptionEvent should call resolve
     Failure/Error: SubscriptionEventResolver.any_instance.should_receive(:resolve)
       (#<Mocha::ClassMethods::AnyInstance:0x007f89c40a5488>).resolve(any args)
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/models/subscription_event_spec.rb:66:in `block (2 levels) in <top (required)>'
     # -e:1:in `<main>'

Finished in 0.44287 seconds
1 example, 1 failure

为什么?

(我正在使用rspec-rails(2.14.0)更新所有依赖项。)

2 个答案:

答案 0 :(得分:1)

这对我有用

require 'rspec/autorun'

class SubscriptionEventResolver < Struct.new(:event)
end

describe SubscriptionEventResolver do
  it 'should call resolve' do
    SubscriptionEventResolver.any_instance.should_receive(:resolve)
    SubscriptionEventResolver.new(double().as_null_object).resolve
  end
end

给了我

[17:40] arkham ~/Desktop [2.0.0-p247]
↳ $ ruby resolver_spec.rb
.

Finished in 0.0011 seconds
1 example, 0 failures

也许有其他事情在干扰?

答案 1 :(得分:0)

您是否尝试过:

it 'should call resolve', focus: true do
  resolver = double('resolver')
  resolver.should_receive(:resolve)
  SubscriptionEventResolver.stub(:new).and_return(resolver)

  SubscriptionEventResolver.new(double('argument').as_null_object).resolve
end