【发布时间】:2019-01-23 15:27:36
【问题描述】:
我有一个非常简单的 Pundit 策略,其中包含不同用户角色的范围。我不知道如何在 Rspec 中测试它。具体来说,我不知道如何在访问范围之前告诉范围什么用户登录了。
这是我尝试过的:
let(:records) { policy_scope(Report) }
context 'admin user' do
before(:each) { sign_in(admin_user) }
it { expect(reports.to_a).to match_array([account1_report, account2_report]) }
end
context 'client user' do
before(:each) { sign_in(account2_user) }
it { expect(reports.to_a).to match_array([account2_report]) }
end
当我运行 Rspec 时,我得到:
NoMethodError: undefined method `sign_in' for #<RSpec::ExampleGroups::ReportPolicy::Scope:0x00007f93241c67b8>
我在控制器测试中广泛使用sign_in,但我猜这不适用于策略测试。
Pundit 文档只说:
Pundit 不提供用于测试范围的 DSL。只需像普通的 Ruby 类一样测试它!
那么...有没有人为特定用户测试 Pundit 范围的示例?如何告诉范围 current_user 是什么?
FWIW,这是我政策的精髓:
class ReportPolicy < ApplicationPolicy
def index?
true
end
class Scope < Scope
def resolve
if user.role == 'admin'
scope.all
else
scope.where(account_id: user.account_id)
end
end
end
end
在我的控制器中,我将其称为如下。我已经确认这在现实世界中可以正常工作,管理员可以看到所有报告,而其他用户只能看到他们帐户的报告:
reports = policy_scope(Report)
【问题讨论】:
标签: ruby-on-rails ruby rspec pundit