在存根实例上存根方法时,无法获取should_receive的存根验证

时间:2013-01-14 21:17:48

标签: ruby rspec mocking

我正在尝试将由Koala包装的facebook图形api存根。我的目标是验证图表是否使用给定的访问令牌进行初始化,并调用方法“me”。

我的rspec代码如下:

要求'spec_helper'

describe User do

  describe '.new_or_existing_facebook_user' do
    it 'should get the users info from facebook using the access token' do
      # SETUP
      access_token = '231231231321'
      # build stub of koala graph that expected get_object with 'me' to be called and return an object with an email
      stub_graph = stub(Koala::Facebook::API)
      stub_graph.stub(:get_object). with('me'). and_return({
        :email => 'jame1231231tl@yahoo.com'
      })
      # setup initializer to return that stub
      Koala::Facebook::API.stub(:new) .with(access_token). and_return(stub_graph)

      # TEST
      user = User.new_or_existing_facebook_user(access_token)

      # SHOULD
      stub_graph.should_receive(:get_object).with('me') 
    end
  end
end

模型代码如下:

class User < ActiveRecord::Base
  # attributes left out for demo
  class << self
    def new_or_existing_facebook_user(access_token)
      @graph = Koala::Facebook::API.new(access_token)
      @me = @graph.get_object('me')

      # rest of method left out for demo
    end
  end
end

运行测试时,我收到错误:

  1) User.new_or_existing_facebook_user should get the users info from facebook using the access token
     Failure/Error: stub_graph.should_receive(:get_object).with('me')
       (Stub Koala::Facebook::API).get_object("me")
           expected: 1 time
           received: 0 times
     # ./spec/models/user_spec.rb:21:in `block (3 levels) in <top (required)>'

我怎么把这种方法弄错了?

2 个答案:

答案 0 :(得分:1)

在调用该方法之前,should_receive需要进入。 Rspec消息期望通过接管方法并监听它来工作,非常类似于存根。实际上,您可以将其替换为存根。

在完成规范的其余部分之后,期望将决定是否成功。

请改为尝试:

describe User do

  describe '.new_or_existing_facebook_user' do
    it 'should get the users info from facebook using the access token' do
      # SETUP
      access_token = '231231231321'
      # build stub of koala graph that expected get_object with 'me' to be called and return an object with an email
      stub_graph = stub(Koala::Facebook::API)

      # SHOULD
      stub_graph.should_receive(:get_object).with('me').and_return({
        :email => 'jamesmyrtl@yahoo.com'
      })

      # setup initializer to return that stub
      Koala::Facebook::API.stub(:new).with(access_token).and_return(stub_graph)     

      # TEST
      user = User.new_or_existing_facebook_user(access_token)
    end
  end
end

答案 1 :(得分:1)

首先,我不会使用stub,因为存根表明您很可能不关心对象的行为。您应该使用mock,即使它们实例化相同的东西。这更清楚地表明你想测试它的行为。

您的问题来自您在测试后设定的期望。您需要在测试之前设置期望值才能进行注册。