Ask A Question


You’re not receiving notifications from this thread.

Testing and Session Variables

Dan Tappin asked in Testing

In my Rails 5 app I am using Pundit for authorization with a custom context. I have a multi-tenant application and I have an Enrollment model that joins my User and Tenant model. This was a single user can have authorization scoped to the tenant. The app works fine - the tests not so much.

Here is some of my code (built by a third party a while back):

class ApplicationPolicy
  attr_reader :enrollment, :record

  def initialize(enrollment, record)
    @enrollment = enrollment
    @record = record

In my application controller current_enrollment is set from a session variable.

So here is a typical policy:

  def download?
    return true if enrollment.has_role?('administrator')

Thats a valid fixture but my tests will fail with NoMethodError: undefined method 'has_role?' for nil:NilClass. Clearly the enrollment in the policy is not set. Done lots of searching on this but could not find another similar question etc.

It's not a Pundit issue - the session variables seem to not be set in test environment.


I had a rouge conditional wrapped around my code where I set the enrollment. This fails in testing but passes in production. Tweaked that and now it works fine.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.