rspec-rails - 如何使用 cancancan 为能力编写 rspec
问题描述
我已经实现了帖子和用户模型,其中帖子模型属于用户模型。我定义了授权的能力模型,这样只有创建帖子的用户才能删除或更新帖子。我有这样的后控制器:
def edit
@post = @topic.posts.find(params[:id])
authorize! :update, @post
end
能力模型:
class Ability
include CanCan::Ability
def initialize(user)
can :update, Post do |p|
p.user == user
end
can :destroy, Post do |p|
p.user == user
end
can :destroy, Comment do |c|
c.user == user
end
can :create, Post
can :create, Comment
end
end
上述模型的 rspec 是什么?错误:
expected #<User id: nil, email: "", created_at: nil, updated_at: nil> to respond to `able_to?`
0) User Check for Abilities What User can do should be able to :create and #<Post id: nil, title: nil, body: nil, created_at: nil, updated_at: nil, topic_id: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, user_id: nil>
Failure/Error: it { should be_able_to(:create, Post.new) }
expected #<User id: nil, email: "", created_at: nil, updated_at: nil> to respond to `able_to?`
# ./spec/models/ability_spec.rb:8:in `block (4 levels) in <top (required)>'
expected #<User id: nil, email: "", created_at: nil, updated_at: nil> to respond to `able_to?`
0) User Check for Abilities What User can do should be able to :update and #<Post id: nil, title: nil, body: nil, created_at: nil, updated_at: nil, topic_id: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, user_id: nil>
Failure/Error: it { should be_able_to(:update, Post.new) }
expected #<User id: nil, email: "", created_at: nil, updated_at: nil> to respond to `able_to?`
# ./spec/models/ability_spec.rb:9:in `block (4 levels) in <top (required)>'
解决方案
根据您提供的有限信息,我将分享一个spec
测试能力的示例。
describe "User" do
describe "Check for Abilities" do
let(:user) { FactoryGirl.create(:user) }
describe "What User can do" do
it { should be_able_to(:create, Post.new) }
it { should be_able_to(:update, Post.new) }
end
end
end
我在顶部提供的是一个示例,您必须使用它来构建它。我更新的答案
require "cancan/matchers"
describe "User" do
describe "abilities" do
user = User.create!
ability = Ability.new(user)
expect(ability).to be_able_to(:create, Post.new)
expect(ability).to_not be_able_to(:destroy, Post.new)
end
end
推荐阅读
- docker - Updating container on VM. How?
- json - Jolt transformation array
- python - Unable to access User object in models.py of Post app: Django
- jquery - JQuery Toggle visibility of divs
- python - How do I have user input in this sqlite query with pandas?
- aspectj - 单元测试 pomless aspectJ 项目
- primary-key - 有重复的雪花
- http - Flutter web http请求badCertificateCallback
- delphi - Delphi在工作线程中断开TIdTCPClient
- linux - 如何使用 UNIX 将标题附加到多标题 csv 文件中的剩余行