classApplicationController<ActionController::Baseprotect_from_forgeryincludePunditrescue_fromPundit::NotAuthorizedError,with::user_not_authorizedprivatedefuser_not_authorizedflash[:alert]="You are not authorized to perform this action."redirect_to(request.referrer||root_path)endend
RSPEC
基本上 github 上面就非常清楚了
12
#rails_helper.rbrequire"pundit/rspec"
12345678910111213141516171819
#spec/policiesdescribePostPolicydosubject{described_class}permissions:update?,:edit?doit"denies access if post is published"doexpect(subject).not_topermit(User.new(admin:false),Post.new(published:true))endit"grants access if post is published and user is an admin"doexpect(subject).topermit(User.new(admin:true),Post.new(published:true))endit"grants access if post is unpublished"doexpect(subject).topermit(User.new(admin:false),Post.new(published:false))endendend