How do I create a spec that verifies that Pundit rejects users who are not logged in?

I am using Pundit gem for authorization in my closed Ruby on Rails application (using Rails 4.1.5 and Rspec 3.0)

I configured my application's policy to throw an exception if the user is not defined as recommended in the Pundit documentation:

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

      

How do I write a specification that verifies that every Pundit policy rejects the nil user?

I made the following attempt:

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

      

But he's with a mistake

 Failure/Error: expect(PostPolicy.new(nil, record)).to raise_error(Pundit::NotAuthorizedError)
 Pundit::NotAuthorizedError:
   must be logged in

      

Any suggestions for proper testing?

+3


source to share


1 answer


RSpec cannot catch the error in the background unless you use a raise_error

-server with a block formexpect

:

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

      



As an alternative

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

      

+5


source







All Articles