我在测试中有这个:
let(:ability) { Object.new.extend(CanCan::Ability) }
...
describe "GET show" do
it 'redirects to root if havent read ability' do
allow(@controller).to receive(:current_ability).and_return(ability)
ability.cannot :read, Book
get :show, { id: '1'}
response.should redirect_to(root_url)
end
...
在 Controller 中,我有来自 cancan 的 load_and_authorize_resource,当测试运行时,它尝试从 id = 1 的数据库中获取记录。我只需要测试 authorize_resource,而不是负载。
我已经通过在调用 get 之前在 Controller 中设置实例变量来修复它:
@controller.instance_variable_set('@author', true) # to skip load_resource
但这不是完美的决定。在使用 load_and_authorize_resource 的 Controller 中测试能力时,跳过加载并仅检查 authorize_resource 是一种更好的方法吗?
最佳答案
好像
allow_any_instance_of(CanCan::ControllerResource).to receive(:load_resource)
工作正常
关于ruby-on-rails - 如何在 Controller 能力测试中 stub load_and_authorize_resource 的负载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22012241/