如何在控制器能力测试中模拟 load_and_authorize_resource 的加载?

4

我在测试中有这个:

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
...

在控制器中,我使用了Cancan中的load_and_authorize_resource,并且在测试运行时,它尝试从数据库中获取id = 1的记录。我只需要测试authorize_resource,而不是load。

我已经通过在调用get之前在控制器中设置实例变量来解决了这个问题:

@controller.instance_variable_set('@author', true) # to skip load_resource

但这并不是最完美的决策。在控制器中测试权限时,是否有更好的方法可以跳过加载并仅检查authorize_resource呢?使用load_and_authorize_resource可以实现此目的。

1个回答

2

看起来像是

allow_any_instance_of(CanCan::ControllerResource).to receive(:load_resource)

运行良好


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接