pundit: undefined method 'policy' in view when running RSpec + Capybara test

I have an Rspec (2.14) test that fails when I try using the policy() helper in my view. The spec fails saying the policy method is not available. When I view the page in my browser it works fine and I don’t get an error. I’ve never seen something like this happen before where a helper was not available in a spec, so I figured I’d open a ticket in case someone had run into this before.

The error:

ActionView::Template::Error:
  undefined method `policy' for #<#<Class:0x0000000ab4ae60>:0x0000000ab4a4d8>

Code from my view when it’s failing:

<% if policy(Subscription::Free.new).create? %>

If I update my template to the following it works in both the browser and specs, so I have a workaround, but it’s odd.

<% if SubscriptionPolicy.new(current_user, Subscription::Free.new).create? %>

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 4
  • Comments: 19

Most upvoted comments

Running into this with a view spec on a new Rails 5 project, trying to determine what’s different now.

I also have this problem and would like to not have to use a workaround.

It seems like almost 9 years on this is still an issue. new project, rails 7, view spec…

undefined method 'policy' for #<ActionView::Base

any updates on how to fix this issue?

Same issue with Rails 7 in a helper spec for

# xyz_helper.rb
def download_link(record)
  link_to(...) if policy([:admin, record]).download?
end

with

NoMethodError:
   undefined method `policy' for #<ActionView::Base:

Still nothing on this and https://github.com/elabs/pundit/issues/339 was also closed. Is nobody bothering with view specs at this point?

This was me being a total idiot. I was sharing a partial with a view that was not subclassing the ApplicationController. 😬

Is Pundit included in the ApplicationController? (See the Readme)

class ApplicationController < ActionController::Base
  include Pundit
  ...
end