[英]Rails rspec test for controller cancan abilities
I would like to write a test to make sure that "expert" users can create articles, and "basic" users cannot. 我想写一个测试,以确保“专家”用户可以创建文章,“基本”用户不能。 For example, basic user cannot go here:
"http://0.0.0.0:3000/articles/new"
. 例如,基本用户不能到这里:
"http://0.0.0.0:3000/articles/new"
。 Below is a shortened version of my articles controller, followed by the articles test. 下面是我的文章控制器的缩短版本,然后是文章测试。 The controller works, but I would like the test to prove it out.
控制器工作,但我想测试证明它。 I'm not sure what to put where it says "code goes here".
我不知道该怎么说“代码在这里”。 Thanks.
谢谢。
articles_controller: 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: 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
Testing CanCan abilities from your Controllers' specs will blow up your specs soon. 从您的控制器规格测试CanCan功能将很快破坏您的规格。
I prefer to test abilities in spec/models/ability_spec.rb using cancan/matchers 我更喜欢使用cancan / matchers测试spec / models / ability_spec.rb中的能力
in your spec file, you can do it like: 在您的spec文件中,您可以这样做:
describe "create article" do
it "should not create new article" do
get :new
expect(response).not_to render_template("new")
end
end
In document of cancan , see https://github.com/ryanb/cancan/wiki/Testing-Abilities , you can get details. 在cancan文档中,请参阅https://github.com/ryanb/cancan/wiki/Testing-Abilities ,您可以获取详细信息。
Instead of testing what shouldn't happen, consider the simpler test of what should happen: 而不是测试不应该发生的事情,考虑更简单的测试应该发生什么:
it "should return 401" do
get :new
expect(response.status).to eq(401)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.