[英]Rails rspec test for controller cancan abilities
我想寫一個測試,以確保“專家”用戶可以創建文章,“基本”用戶不能。 例如,基本用戶不能到這里: "http://0.0.0.0:3000/articles/new"
。 下面是我的文章控制器的縮短版本,然后是文章測試。 控制器工作,但我想測試證明它。 我不知道該怎么說“代碼在這里”。 謝謝。
articles_controller:
class ArticlesController < ApplicationController
load_and_authorize_resource
# GET /articles/new
# GET /articles/new.json
def new
puts "in articles new"
@article = Article.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @article }
end
end
end
articles_controller_spec:
describe ArticlesController do
before (:each) do
@user = FactoryGirl.create(:user)
@user.role = "basic"
sign_in @user
end
describe "create article" do
it "should not create new article" do
#code goes here
end
end
end
從您的控制器規格測試CanCan功能將很快破壞您的規格。
我更喜歡使用cancan / matchers測試spec / models / ability_spec.rb中的能力
在您的spec文件中,您可以這樣做:
describe "create article" do
it "should not create new article" do
get :new
expect(response).not_to render_template("new")
end
end
在cancan文檔中,請參閱https://github.com/ryanb/cancan/wiki/Testing-Abilities ,您可以獲取詳細信息。
而不是測試不應該發生的事情,考慮更簡單的測試應該發生什么:
it "should return 401" do
get :new
expect(response.status).to eq(401)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.