[英]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.