2011-05-12 83 views
3

現在,我有CanCan和Devise很好地工作,我需要添加到我的測試。測試設計和cancan在控制器規格(rspec)

我是否應該期望結束雙倍的測試,也許更多?我需要將所有內容作爲「訪客」用戶進行測試,然後以用戶身份和管理員身份進行測試。

用rspec你將如何解決這個問題?

describe "GET edit" do 
    login_admin 
    it "assigns the requested forum_topic as @forum_topic" do 
     ForumTopic.stub(:find).with("37") { mock_forum_topic } 
     get :edit, :id => "37" 
     response.should redirect_to(new_user_session_path) 
    end 

    it "assigns the requested forum_topic as @forum_topic" do 
     ForumTopic.stub(:find).with("37") { mock_forum_topic } 
     get :edit, :id => "37" 
     assigns(:forum_topic).should be(mock_forum_topic) 
    end 
end 

幫助模塊

def login_admin 
    before(:each) do 
     @request.env["devise.mapping"] = Devise.mappings[:admin] 
     sign_in Factory.create(:admin) 
    end 
    end 

    def login_user 
    before(:each) do 
     @request.env["devise.mapping"] = Devise.mappings[:user] 
     @user = Factory.create(:user) 
     sign_in @user 
    end 
    end 

回答

2

測試慘慘時,正在測試的能力,文件本身是通常完成。

例如,如果你測試你的應用程序,你應該能夠看到某個論壇,除非簽訂,你可以測試一下,像這樣:

@user = Factory.create(:user) 
@forum = Factory.create(:forum) 

describe "User ability" do 
    it "Should be able to view forums" do 
    @ability = Ability.new(@user) 
    @ability.should be_able_to(:show, @forum) 
    end 
end 

describe "nil ability" do 
    it "Should be not be able to view forums if not signed in" do 
    @ability = Ability.new(nil) 
    @ability.should_not be_able_to(:show, @forum) 
    end 
end 

這僅僅是一個例子。

您可以閱讀更多關於它:https://github.com/ryanb/cancan/wiki/Testing-Abilities

最後測試設計我只是做集成測試與水豚,並與管理員和用戶登錄。