[rspec-users] Mocking Access Control

Courtenay court3nay at gmail.com
Fri Jul 27 16:55:16 EDT 2007


On 7/27/07, Justin Williams <carpeaqua at gmail.com> wrote:
> Thanks for the help.
>

You're welcome

> I think I'm getting closer.  I'm still not getting a redirect.  I
> still think it's the same reason though.  I say this because when I
> modify the last line of my spec to be render_template("index") instead
> of redirect, it says that it renders the login template.
>
> Am I putting the should_receive for has_role? in the wrong place?
>
> My modified code is below.
>
> def login
>   if request.post?

Have you seen the restful authentication plugin? It would simplify your code.
I modified it for rSpec. You can view it in a working app here:
  http://sample.caboo.se/empty_rails_app/trunk/app/controllers/session_controller.rb

>   begin
>     session[:user] = User.authenticate(params[:login][:email],
> params[:login][:password]).id
>
>     # Redirect the user as appropriate
>     if current_user.has_role?("tutor")
>       redirect_to toolkit_path
         return

  Add a return here.  You should get in the habit of putting a
"return" after a redirect

>     end
>   rescue
>     flash[:warning] = "Your e-mail address or password is invalid."
>     render :action => "login"
>   end
>   end
> end
>
> ------
>
> describe UsersController do
>   controller_name :users
>
>   before(:each) do
>     @current_user = mock_model(User,
>       :email => 'teamup at teamup.host',
>       :password => 'teamup'
>     )
>     controller.stub!(:current_user).and_return(@current_user)
>   end
>
>   it "should login as a tutor" do

These two lines aren't needed:

>     @role = mock_model(Role, :title => 'tutor')
>     @current_user.should_receive(:roles).once.and_return([@role])

  The point of refactoring the role stuff into "has_role?" is that the
implementation of "has_role" could be anything.

  See how your controller doesn't know anything about "User.has_role?"
  Your test shouldn't either.  Just assume that it works.  And test it
in the user model specs.

Put this line before the authenticate line and it all should work.

  @current_user.should_receive(:has_role?).with('tutor').and_return true

>     User.should_receive(:authenticate).with(@current_user.email, at current_user.password).and_return(@current_user)
>

>     @current_user.should_receive(:has_role?).with('tutor').and_return(true)
>     post :login, :login => {:email => @current_user.email, :password
> => @current_user.password}
>     request.session[:user].should == @current_user.id
>
>     should_be_logged_in
>
>     response.should be_redirect
>     response.should redirect_to(toolkit_path)
>   end
> end
>


More information about the rspec-users mailing list