我在我的封闭系统 Ruby on Rails 应用程序(使用 Rails 4.1.5 和 Rspec 3.0)上使用 Pundit gem 进行授权
我已将我的应用程序策略配置为在未按照 Pundit 文档中的建议定义用户时引发异常:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
@user = user
@record = record
end
end
我如何编写一个规范来验证每个 Pundit 策略是否拒绝一个 nil 用户?
我做了以下尝试:
RSpec.describe PostPolicy do
it "should raise an exception when users aren't logged in" do
expect(AccountFolderPolicy.new(nil, record)).to raise_error(Pundit::NotAuthorizedError)
end
end
但是它出错了
Failure/Error: expect(PostPolicy.new(nil, record)).to raise_error(Pundit::NotAuthorizedError)
Pundit::NotAuthorizedError:
must be logged in
关于如何正确测试它有什么建议吗?
最佳答案
除非你 use the raise_error
matcher with the block form of expect
,否则 RSpec 无法在后台捕获错误:
RSpec.describe PostPolicy do
it "should raise an exception when users aren't logged in" do
expect do
AccountFolderPolicy.new(nil, record)
end.to raise_error(Pundit::NotAuthorizedError)
end
end
或者
RSpec.describe PostPolicy do
it "should raise an exception when users aren't logged in" do
expect { AccountFolderPolicy.new(nil, record) }.to raise_error(Pundit::NotAuthorizedError)
end
end
关于ruby-on-rails - 如何创建一个规范来验证 Pundit 拒绝未登录的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362560/