Dondo Land

Bryan Donovan's Weblog

All | General | Music | Rails

20071215 Saturday December 15, 2007

 Handling authenticated users with RSpec

Nothing new here, but thought I would share something that set me back a bit when first learning RSpec and testing controllers. If you're using a user authentication system like acts_as_authenticated, you have a method available in your controllers called "current_user" which of course returns the currently logged in user. To simulate this in a controller spec using RSpec, you can tell the controller to return a mock User object when current_user is called:

before do
  controller.stub!(:current_user).and_return(mock_model(User, :to_param => "1"))
end

Of course you may have to change the :to_param value to something else, depending on what you're testing (e.g., maybe different users have different roles/permissions).

Thanks to Igal Koshevoy for the last tip I needed to get this working. Igal wrote the awesome AutomateIt open source tool for automating the setup and maintenance of servers, applications and their dependencies.



(2008-02-02 14:36:56.0/2007-12-15 13:36:57.0) Permalink Comments [2]
Trackback: http://blogs.sun.com/bdonovan/entry/handling_authenticated_users_with_rspec


« December 2007 »
SunMonTueWedThuFriSat
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
     
Today


XML







Today's Page Hits: 13