<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: controller code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 26 Jul 2008 22:54:25 GMT</pubDate>
    <description>DZone Snippets: controller code</description>
    <item>
      <title>#post method in tests with a different controller</title>
      <link>http://snippets.dzone.com/posts/show/2880</link>
      <description>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 &lt;a href="http://api.rubyonrails.org/classes/ActionController/TestProcess.html#M000046"&gt;#process method&lt;/a&gt; works, you can see that it just grabs the controller from @controller.  Redefine that, and you're good to go:&lt;br /&gt;&lt;code&gt;old_controller = @controller&lt;br /&gt;@controller = LoginController.new&lt;br /&gt;post(&lt;br /&gt;  :attempt_login,&lt;br /&gt;  {:user =&gt; {:name =&gt; 'joe', :password =&gt; 'password'}}&lt;br /&gt;)&lt;br /&gt;@controller = old_controller&lt;/code&gt;&lt;br /&gt;If you have several login methods, such as a #login_admin and #login_regular, you could make a wrapper to reduce duplication:&lt;br /&gt;&lt;code&gt;def wrap_with_controller( new_controller = LoginController )&lt;br /&gt;  old_controller = @controller&lt;br /&gt;  @controller = new_controller.new&lt;br /&gt;  yield&lt;br /&gt;  @controller = old_controller&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def login_admin&lt;br /&gt;  wrap_with_controller do&lt;br /&gt;    post(&lt;br /&gt;      :attempt_login,&lt;br /&gt;      {:user =&gt; {:name =&gt; 'root', :password =&gt; 'password'}}&lt;br /&gt;    )&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def login_regular&lt;br /&gt;  wrap_with_controller do&lt;br /&gt;    post(&lt;br /&gt;      :attempt_login,&lt;br /&gt;      {:user =&gt; {:name =&gt; 'joe', :password =&gt; 'password'}}&lt;br /&gt;    )&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Tue, 24 Oct 2006 18:54:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2880</guid>
      <author>moneypenny ()</author>
    </item>
  </channel>
</rss>
