ruby-on-rails - 如何创建一个规范来验证 Pundit 拒绝未登录的用户?

标签 ruby-on-rails ruby rspec pundit

我在我的封闭系统 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/

相关文章:

ruby-on-rails - CSV - 未加引号的字段不允许\r 或\n(第 2 行)

mysql - 循环遍历 Rails 中的多个属性

带有 ca 认证的 Ruby https 在与 curl 一起工作时不起作用

ruby-on-rails - 在Rspec和Rails中验证 bool 值

ruby-on-rails - 如何让 Rails 从本地源目录中获取 gem?

ruby-on-rails - Rails 查询 : find first record by id and select only specified attributes for that record

ruby-on-rails - 如何在 Ruby 中使用 RSpec 通过 Windows 命令提示符获取颜色?

ruby - 如何在 rspec 示例之间设置一些依赖关系?

ruby-on-rails - 如何使用Docker安装Guard-Test?

ruby - 如何通过元编程解决这个问题?