title: How do I create a spec which verifies Pundit rejects users that are not logged in?
body: <p>I'm using the Pundit gem for authorization on my closed system Ruby on Rails application (using Rails 4.1.5 and Rspec 3.0)</p>
  
  <p>I've configured my application policy to raise an exception when the user is not defined as recommended in the Pundit documentation:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>How can I write a spec which verifies that each Pundit policy rejects a nil user?</p>
  
  <p>I made the following attempt:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>But it errors out with </p>
  
  <pre><code> Failure/Error: expect(PostPolicy.new(nil, record)).to raise_error(Pundit::NotAuthorizedError)
   Pundit::NotAuthorizedError:
     must be logged in
  </code></pre>
  
  <p>Any suggestions on how to properly test this?</p>