How to access a Rails controller view context from outside of a controller?

Andrew picture Andrew · Jan 9, 2015 · Viewed 11.8k times · Source

I am working on cleaning up some code that relies on some custom controller helper methods, by creating a "plain old Ruby" presenter object. In my controller, I am able to pass the view context to the class:

def show
  # old code: view_context.bad_helper_method
  @foobar = FoobarPresenter.new(Foobar.find(params[:id]), view_context)
end

class FoobarPresenter
  def initialize(model, view_context)
    @model = model
    @view_context = view_context
  end

  def something
    @view_context.bad_helper_method
  end
end

However, I'm not sure what to pass in my test. I would rather pull the helper/view_context dynamically so that I don't have to pass it in.

How can I access the view/controller helper context outside of the controller?

This is a Rails 3.2 project.

Answer

Jesus Monzon Legido picture Jesus Monzon Legido · Mar 1, 2017

Simpler than you think! (I lost almost an hour until I found a way)

You can instantiate an ActionView

_view_context = ActionView::Base.new

and use it in your test

FoobarPresenter.new(Foobar.new, _view_context)