我正在尝试为我的 Restaurant
模型运行一个强大的参数测试,但我遇到了一个错误,该错误阻碍了开发的进展。在它的 Controller 中,我有 CanCan 方法 load_and_authorize_resource
只允许管理员创建、更新和销毁这些模型实例:
class RestaurantsController < ApplicationController
load_and_authorize_resource param_method: :restaurant_params, find_by: :slug
...
end
在运行测试时出现错误:
1) RestaurantsController should permit POST #create to receive parameters :name
Failure/Error: should permit(:name).
CanCan::AccessDenied:
You are not authorized to access this page.
有没有简单的方法绕过这个授权?我在整个 SO 中都看过了,似乎没有一个明确的答案。
测试
describe RestaurantsController do
let(:user) { FactoryGirl.create(:user, admin: true) }
it { should permit(:name).for(:create) }
end
注意:我已经查看了 docs在 CanCan 上,他们说要创建一个用户实例,其 admin 属性设置为 true。尽管如此,我仍然对如何在我的测试中插入该用户感到困惑。
最佳答案
经过一些研究,我得出结论,绕过此问题的最佳方法与通过 Devise 登录 我的 User
工厂有关。不仅仅是处理 CanCanCan gem 本身。
根据您的设置,这可能会有所不同,但对于我的用户工厂,我将我的 admin
属性设置为 true
。
用户.rb
FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
email "john@example.com"
password "password"
admin true
end
end
然后我在我的 spec
文件夹中创建了一个名为 support
的子目录,并按照提供的 Devise 链接中的示例创建用于登录用户的适当模块方法:
spec/support/controller_macros.rb
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:admin]
sign_in FactoryGirl.create(:user)
end
end
end
然后在我的 rails_helper
文件中,我简单地扩展了这个模块,以便我可以使用 login_admin
方法。 Devise 示例没有提到的是您需要要求
此助手中的controller_macros
文件。它可能会被某些人理解,但如果不小心可能会被忽视:
spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'support/controller_macros'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
....
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
end
最后,在您的 Controller 测试中,只需在需要的地方应用 login_admin
方法:
餐厅 Controller 测试
describe RestaurantsController do
login_admin
it { should permit(:name).for(:create) }
end
关于ruby-on-rails - 在运行 RSpec 测试时绕过 CanCan::AccessDenied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31762307/