0

我正在尝试对 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)>'

我如何存根该方法是错误的?

4

2 回答 2

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
于 2013-01-14T21:24:13.087 回答
1

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

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

于 2013-01-14T21:27:25.067 回答