2010-11-15 78 views
1

我刚刚实现了OmniAuth(使用Ryan Bates的Screencast http://asciicasts.com/episodes/235-omniauth-part-1),并且正在为此功能编写Rspec测试,并遇到了测试验证#创建操作的麻烦。我对如何测试这个问题感到茫然 - 特别是如何存根局部变量omniauth。无论我尝试什么,我都不能得到任何测试工作。如何在rspec控制器测试中存根局部变量

采取的行动削减版本,你会如何测试一个新的被称为上的用户例如


#cut down version of the authentifications controller code I am attempting to test 

    def create 
    omniauth = request.env["omniauth.auth"] 
    authentification = Authentification.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])  
    .... 
    user = User.new 
    .... 
    end 

#example test 

    it "should create a new user" do   
     subject.stub_chain(:request,:env) {{"omniauth.auth" => {'provider' =>1, 'uid' => 2}}} 
     User.should_receive(:new) 
     post :create 
     end 

回答

3

我这样做:

class SessionsController < ApplicationController 
    def create 
    @user = User.find_by_auth_hash(auth_hash) 
    end 

    def auth_hash 
    request.env['omniauth.auth'] 
    end 
end 

describe SessionsController do 
    it 'should allow login' do 
    controller.stub!(:auth_hash).and_return({'provider' => 'twitter', 'uid' => '1234'}) 
    get :create, :provider => 'twitter' 
    assigns(:user).should_not be_nil 
    end 
end 

希望这有助于。

+0

auth_hash的那个可爱的小重构完成了工作。 – 2010-11-25 12:11:27