ruby-on-railsrubyrspec

How to make helper_methods available to Views in Rspec


We have some helper_methods in our controllers that are used across both the controller and the view they render.

For example:

helper_method :example_method
def example_method
  @example_method ||= nil
end

However when it comes to testing our views in Rspec we have hit errors that those methods don't exist (likely because the views are tested in isolation from the controller).

ActionView::Template::Error:
       undefined local variable or method `example_method' for #<ActionView::Base:0x0000000003b060>

We've tried mocking the methods in the specs like:

allow(view).to receive(:example_method).and_return(nil)

But that doesn't resolve the issue.

I know Devise solved this with their controller helpers: https://github.com/heartcombo/devise/blob/fec67f98f26fcd9a79072e4581b1bd40d0c7fa1d/lib/devise/test/controller_helpers.rb and then including them into the Rspec setup:

config.include Devise::Test::ControllerHelpers, type: :view

Which means your views can access current_user, etc.

But it's not clear how to replicate this for our custom helper methods.


Solution

  • So I managed to solve this by wrapping the stub with: without_partial_double_verification like so:

      before do
        without_partial_double_verification {
          allow(view).to receive(:example_method).and_return(nil)
        }
      end