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

まずstub、スタブはオブジェクトの動作に関心がない可能性が高いことを示しているため、使用しません。mock同じものをインスタンス化する場合でも、代わりに使用する必要があります。これは、その動作をテストしたいことをより明確に示しています。

あなたの問題はあなたがテストの後に期待を設定しているということから来ています。テストを登録するには、テストの前に期待値を設定する必要があります。

于 2013-01-14T21:27:25.067 に答える
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 に答える