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.
Devise::Test::ControllerHelpers. Devise is based on the Warden middleware and the helper methods it generates do not work outside of the context of a HTTP request going through the middleware stack. Controller tests/specs (which you should not be using) don't, and the same applies to view specs. What the module provides is stubs. Despite the name the things are not connected.helper_method :example_methodsimply addscontroller.send(:example_method,...), so since yourviewdoes not technically have aControllerthis is going to be very difficult to test "in isolation", without completely mocking the entire concept, which you could do by simply defining a method (or if you need more methods creating your own module and including it) in thevieweigenclass.helpers.method_namein the controller.