2011-05-12 37 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

最后测试设计我只是做集成测试与水豚,并与管理员和用户登录。