[英]testing devise and cancan in controller specs (rspec)
現在我有CanCan和Devise很好地工作,我需要添加到我的測試中。
我應該期望最終測試次數增加一倍,或許更多嗎? 我需要將所有內容作為“訪客”用戶進行測試,然后作為用戶和管理員進行測試。
有了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
測試CanCan時通常會做的是測試能力文件本身。
例如,如果你在你的應用程序中測試它,你應該無法查看某個論壇,除非簽名你可以測試它如下:
@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
最后測試設計我只是與capybara進行集成測試,並使用admin和user登錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.