<br><br><div class="gmail_quote">On Tue, Apr 8, 2008 at 10:03 AM, Giuseppe Bertini &lt;<a href="mailto:lists@ruby-forum.com">lists@ruby-forum.com</a>&gt; wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Dear all,<br>
<br>
I am wondering how to properly mock/stub out the preliminary steps to<br>
actions protected by restful_authentication and acl_system2 (role-based<br>
authorization to execute actions). Here&#39;s my setup:<br>
</blockquote><div><br>I use a different authorization plugin, so you might have to adapt, but I&#39;ve got the following in my spec_helper:<br><br>def as_role(roles = [])<br>&nbsp; returning User.new do |user|<br>&nbsp; &nbsp; # This will become stub_model whenever 1.1.4 comes out ...<br>
&nbsp;&nbsp;&nbsp; <a href="http://user.id">user.id</a> = 2000<br>&nbsp; &nbsp; user.stub!(:new_record?).and_return false<br>&nbsp;&nbsp;&nbsp; user.stub!(:valid?).and_return true<br><br>&nbsp; &nbsp; if @controller<br>&nbsp; &nbsp; &nbsp; @controller.stub!(:login_required).and_return true<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @controller.stub!(:current_user).and_return true<br>&nbsp;&nbsp; &nbsp;&nbsp; @controller.stub!(:logged_in?).and_return true<br>&nbsp;&nbsp;&nbsp; end<br><br>&nbsp; &nbsp; user.stub!(:has_role?).and_return false&nbsp; # because has_role? hits the DB<br>&nbsp;&nbsp;&nbsp; [*roles].map(&amp;:to_s).each do |role|<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; user.stub!(&quot;is_#{role}?&quot;).and_return true<br>&nbsp;&nbsp; &nbsp;&nbsp; user.stub!(:has_role?).with(role).and_return true<br>&nbsp;&nbsp;&nbsp; end<br>&nbsp; end<br>end<br>alias :logged_in :as_role<br><br></div></div><br>This returns a User, and can be used in either the controller or in model specs, to deal with various aspects of a roled user.&nbsp; You can call it with an array of roles, or a single role; it deals with it either way.&nbsp; The last alias is because logged_in looks better than as_role without any arguments.<br>
<br clear="all"><br>-- <br>// anything worth taking seriously is worth making fun of<br>// <a href="http://blog.devcaffeine.com/">http://blog.devcaffeine.com/</a>