Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

#post Method In Tests With A Different Controller

DZone's Guide to

#post Method In Tests With A Different Controller

·
Free Resource
I wanted a #login method in test_helper that would allow me to easily login from any of my functional tests.  However, the #post method won't allow you to set a different controller than the one in the @controller instance variable that's defined in your test's #setup.  Well, by looking at how the #process method works, you can see that it just grabs the controller from @controller.  Redefine that, and you're good to go:
old_controller = @controller
@controller = LoginController.new
post(
  :attempt_login,
  {:user => {:name => 'joe', :password => 'password'}}
)
@controller = old_controller
If you have several login methods, such as a #login_admin and #login_regular, you could make a wrapper to reduce duplication:
def wrap_with_controller( new_controller = LoginController )
  old_controller = @controller
  @controller = new_controller.new
  yield
  @controller = old_controller
end

def login_admin
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'root', :password => 'password'}}
    )
  end
end

def login_regular
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'joe', :password => 'password'}}
    )
  end
end
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}